Violation of PRIMARY KEY constraint with Entity Framework 6 , Model one-to-many

c# code-first entity-framework-6

Popular Answer

You are right; the second instance won't be aware that the customer was just added. You can either inform the second instance the customer already exists or you can wrap them both in the same using statement:

var user = new User();
user.Id = Guid.NewGuid();
user.Name = "username";

using (var db = new DbContext())
{   
    user.Customer = new Customer() { Id = customer.Id };  // only need the id
    db.Customers.Attach(user.Customer);
    db.Users.Add(user);
    db.SaveChanges();
}

Entity Framework: generates a new child in the database by attaching an existing child POCO to a new parent POCO.

1
5/23/2017 12:14:44 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow