[英]Entity A contains Entity B, how do I Update A without inserting B (cause it already exists) EF core
So I'm using EF Core 5.0.1 and I have this entity A, which holds a reference to this other entity B.所以我使用的是 EF Core 5.0.1,我有这个实体 A,它包含对另一个实体 B 的引用。
I want to update an entry from A, so it starts to reference an existing B, but whenever I try to, EF core tries to create this entry of B as if it was a new one, thus causing an error (duplicate Id).我想从 A 更新一个条目,因此它开始引用现有的 B,但是每当我尝试时,EF 核心都会尝试创建 B 的这个条目,就好像它是一个新条目一样,从而导致错误(重复的 Id)。 Is it possible to have EF add this reference to the existing B?
是否可以让 EF 将此引用添加到现有 B?
Entity A:实体 A:
public class Customer
{
public string JdeNumber { get; set; }
public string ResponsibleUnit { get; set; }
public string Email { get; set; }
public User RegionalManager { get; set; }
}
Entity B:实体 B:
public class User
{
public string Code { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Group UserGroup { get; set; }
}
Can't suggest an exact answer without looking at your Update
implementation.如果不查看您的
Update
实施,就无法提出确切的答案。 But I think you can do something like this using the DBContext without updating RegionalManager
.但我认为你可以使用 DBContext 做这样的事情而不更新
RegionalManager
。
var customer = context.Customers.First(a => a.JdeNumber == "number_of_existing_customer");
customer.ResponsibleUnit = "Test Unit";
customer.Email = "email@example.com";
context.SaveChanges();
More ways of updating entities can be found here .更多更新实体的方法可以在这里找到。
I think this happens because there isn't any relation between your two classes for User.我认为发生这种情况是因为您的两个 User 类之间没有任何关系。 So, make a relation between Customer and User entity classes by adding a UserId in Customer class.
因此,通过在 Customer class 中添加 UserId,在 Customer 和 User 实体类之间建立关系。 Moreover, the appropriate foreign key should be added through ModelBuilder.
此外,应通过模型构建器添加适当的外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.