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

前端 未结 4 880
感动是毒
感动是毒 2021-01-25 17:00

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;
  ..         


        
相关标签:
4条回答
  • 2021-01-25 17:11
    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.

    0 讨论(0)
  • 2021-01-25 17:13
    • 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
    0 讨论(0)
  • 2021-01-25 17:19

    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; }
    
    0 讨论(0)
  • 2021-01-25 17:24

    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.

    0 讨论(0)
提交回复
热议问题