Entity Framework inserting duplicates on Seeding database [duplicate]

こ雲淡風輕ζ 提交于 2019-12-02 08:31:48

Your addresses and languages are persisted wheren you advise them to customer. I think in your constructor you advise the collections to customer, din't you? This isn't neccessary. You can persist the customer without an expliciet advise of the collections. EF will map the collections by it self.

I see a few issues with your code. By convention, an int column called ID is going to be an identity column so you can't set it's ID explicitly without issuing a SET IDENTITY_INSERT Language ON (unless you have fluent code overriding this).

AddOrUpdate is intended for these situations. You have not shown that code. Another way is shown below:

...
if (!ctx.Languages.Any(l => l.ID == 1))  // Check if already on file
{
    ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Language ON");  // Omit if not identity column
    var dutch = new Language {
        ID = 1,
        Name = "Dutch",
        Code = "NL"
    };
    ctx.Languages.Add(dutch);
    ctx.SaveChanges();
    ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Language OFF"); // Omit if not identity column
}
... repeat for other languages
... similar code for other seeded tables

So changing the relation in the Address Class of the Entity Customer to a ICollection instead of 1 Single Customer doesn't create a dupe (and creates a CustomerAddress table which i actually want as well).

Seems from the database logs (log4net) that due to the relation EF is first inserting a Customer (NULL) for the Address Reference of the customer, AND inserts the Customer (NOT NULL) with its references ... When i compare Address & Language I see that Language has a Collection of Customers as well (which Address didn't), this explains why Address was creating the duplicate customer entry. (If anyone needs any clarification on this let me know ill do my best)

This post HAS MOVED TO HERE

I want to thank everyone that has contributed in any way!

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