mchouteau
mchouteau

Reputation: 56

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

I have 2 models with one to many relation, if I save in different instance of DbContext, this throw an exception (Violation of Primary Key) - how to avoid it?

public class Customer
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Customer Customer { get; set; }
}

public class DbContext : System.Data.Entity.DbContext
{
    public DbContext()
    : base(@"Data Source=(localdb)\MSSQLLocalDB; AttachDBFilename='|DataDirectory|\Sample.mdf'; Integrated Security=True")
    {
        Configuration.ProxyCreationEnabled = false;
        Configuration.AutoDetectChangesEnabled = true;
        Configuration.ValidateOnSaveEnabled = true;
        Configuration.LazyLoadingEnabled = true;
    }

    public IDbSet<Customer> Customers { get; set; }
    public IDbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<Guid>()
        .Where(p => p.Name == "Id")
        .Configure(p => { p.IsKey(); p.IsRequired(); });
    }
}

AppDomain.CurrentDomain.SetData(
    "DataDirectory",
    System.Environment.CurrentDirectory);

var customer = new Customer();
customer.Id = Guid.NewGuid();
customer.Name = "customername";

using (var db = new DbContext())
{
    db.Customers.Add(customer);
    db.SaveChanges();
}

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

using (var db = new DbContext())
{
    db.Users.Add(user);
    db.SaveChanges(); // <- Throw here
}

of course this is a simplified sample, in what is written it is possible to use only one instance of DbContext, but in reality the customer is passed as a parameter to a method

Upvotes: 0

Views: 1708

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

You are correct - the second instance won't know you just added the customer. Either wrap them in the same using statement or you can tell the second instance the customer already exists:

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: adding existing child POCO to new Parent POCO, creates new child in DB

Upvotes: 1

Related Questions