Entity Framework Code First - Cannot insert duplicate key in object 'db'

余生长醉 提交于 2019-12-31 04:53:07

问题


I'm using the new EF code first to one project of mine, and i'm getting a weird error, my mode is:

abstract class Member
{
   public virtual int MemberId;
  ... some other stuff

}

class User : Member
{
    public virtual string Name;
    ... some more props no new key defined
}

class MyDbContext
{
    public DbSet<User> Users {get;set;}
}

The result of the deployment to SQL Server is just ok, i've a Members Table and a Users Table (TPC). Now in my main i've the following code:

static Main()
{
   User x,y;
   using(MyDbContext ctx = new MyDbContext())
   {


    x = ctx.Users.Create();
    y = ctx.Users.Create();
    x.Name = "SomeUser";
    y.Name = "SomeUser2";
    ctx.SaveChanges();

   }
}

On save changes i get:

"Unhandled Exception: System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for de tails. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient .SqlException: Violation of PRIMARY KEY constraint 'PK_Users_0CF04B1821B6055D'. Cannot insert duplicate key in object 'dbo.Users'."

The MemberId by default is identity so i just not seeing what's going on here. i've tried to create the instances with new and Attach them to the context but the error was the same, any ideas? The database is empty!

Thanks.

EDIT: Forgot to told that Member is an abstract class sorry bout that.


回答1:


I just tested it and tables of derived types in TPC (table per concrete type) inheritance don't have PK defined as identity in EF 4.1 RC.




回答2:


  1. Is MemberId autoIncremented?
  2. Have you checked the id of your created users (with console.Writeline for exemple)?
  3. Does it work if you do the following:

    x = ctx.Users.Create();        
    x.Name = "SomeUser";        
    ctx.SaveChanges();        
    y = ctx.Users.Create();        
    y.Name = "SomeUser2";        
    ctx.SaveChanges();
    

You should try to attach your entity before you modify it.




回答3:


I just came across this. Like the marked answer states, TPC doesn't set the key to an identity. So you can use an annotation for it:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }



回答4:


  • I also had an issue with duplicate keys. For me the reason was that I mistakenly used

    Id = new Guid()

instead of

Id = Guid.NewGuid()

in a factory method for initializing my database.

  • This related stackoverflow question might also give some further hints: Cannot insert duplicate key in object 'dbo.User'.\r\nThe statement has been terminated


来源:https://stackoverflow.com/questions/5449724/entity-framework-code-first-cannot-insert-duplicate-key-in-object-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!