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

梦想与她 提交于 2019-12-02 07:20:58
Ladislav Mrnka

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.

Jean-Philippe Leclerc
  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.

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; }
Stefan
  • 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.

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