简体   繁体   中英

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.

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). Is it possible to have EF add this reference to the existing B?

Entity 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:

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. But I think you can do something like this using the DBContext without updating 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. So, make a relation between Customer and User entity classes by adding a UserId in Customer class. Moreover, the appropriate foreign key should be added through ModelBuilder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM