Error Seeding Database, foreign key issue

后端 未结 1 1692
失恋的感觉
失恋的感觉 2021-01-25 03:43

I have built out my models using POCO. When I go to seed my database I get:

Unable to determine the principal end of the \'CSP.Models.Type_Color\' relationship. Multipl

相关标签:
1条回答
  • 2021-01-25 04:33

    What is happening is your objects all have the default int value (0) for their primary key. When you add them to the context, EF detects this and throws an error (two objects of the same type cannot have the same key, in this case, 0. I assume your primary key fields in the database are set as IDENTITY columns and will auto increment +1 on insert. This may sound odd, but you need to give your objects placeholder IDs which will be replaced on insert with the IDENTITY values.

    new Color{ColorId = 1, Name="Red"},
    new Color{ColorId = 2, Name="White"}
    new Type{TypeId = 1, Name="Hammer", ...}
    new Type(TypeId = 2, Name="Electric", ...}
    
    0 讨论(0)
提交回复
热议问题