gpt4 book ai didi

c# - EF-Core 尝试插入已经存在的关系数据

转载 作者:行者123 更新时间:2023-12-05 04:48:47 25 4
gpt4 key购买 nike

我正在尝试使用 EF-Core 将引用其中其他对象的对象添加到我的数据库中。这是我的两个模型:

    public class Contact : Entity
{
#nullable enable
public string? Name1 { get; set; }
public string? Name2 { get; set; }
public Company? Company { get; set; }
public string? Salutation { get; set; }
public string? Title { get; set; }
public DateTime? Birthday { get; set; }
public string? Address { get; set; }
public string? Postcode { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
public string? Mail { get; set; }
public string? MailSecond { get; set; }
public string? PhoneFixed { get; set; }
public string? PhoneFixedSecond { get; set; }
public string? PhoneMobile { get; set; }
public string? Fax { get; set; }
public string? Url { get; set; }
public string? SkypeName { get; set; }
public bool? IsLead { get; set; }
public string? Remarks { get; set; }
}

public class Company : Entity
{
#nullable enable
public string? Name { get; set; }
public List<Contact>? Contacts { get; set; }
public string? Address { get; set; }
public string? Postcode { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
public string? Url { get; set; }
public string? Remarks { get; set; }
public string? UpdatedAt { get; set; }
}

public class Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? LastEdited { get; set; }
public string? BexioId { get; set; }
}

这是我的 DbContext:

    public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Contact> Contacts { get; set; }

protected override void OnModelCreating(ModelBuilder modelbuilder)
{
modelbuilder.Entity<Contact>().ToTable("Contacts"):
modelbuilder.Entity<Company>().ToTable("Companies");
}
}

尝试使用以下代码插入数据时,出现以下错误:

        public object Add(string values)
{
var newContact = new Models.Contact();
JsonConvert.PopulateObject(values, newContact);

if (!TryValidateModel(newContact))
return BadRequest(ModelState);

_context.Contacts.Add(newContact);
_context.SaveChanges();

return Ok();
}
Microsoft.EntityFrameworkCore.DbUpdateException
HResult=0x80131500
Message=An error occurred while updating the entries. See the inner exception for details.
Source=Microsoft.EntityFrameworkCore.Relational
StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at microtom.portal.Controllers.ContactController.Add(String values) in C:\Users\tpeduzzi\Documents\microtom\microtom.portal\Controllers\ContactController.cs:line 38
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()

This exception was originally thrown at this call stack:
[External Code]

Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'Companies' when IDENTITY_INSERT is set to OFF.

我完全不知道发生了什么。我认为问题在于 EF-Core 试图将对象插入联系人对象的公司字段,即使数据已经在数据库中并且该公司的 Id 字段已经由数据库填写。谁能告诉我我做错了什么?几天来我一直在努力解决这个问题,但我真的很绝望……我正在做网上和亲自告诉我的事情。提前致谢!

最佳答案

_context.Add 之前调用 _context.Attach(newContact.Company)

EF 使用 tracking 的概念查看更改并将它们传播到数据库。在您当前的代码中,newContact.Company 不为空,它作为 newContact 对象图的一部分添加到当前上下文中。由于 context 对这个 Company 一无所知,它将把它视为一个新公司并尝试将其保存到数据库中。 DbContext.Attach默认情况下,使用 Unchanged 状态开始跟踪给定实体和从给定实体可访问的条目,因此它会将其视为现有(且未更改)实体,并且不会尝试将其保存到数据库中。

关于c# - EF-Core 尝试插入已经存在的关系数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67890726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com