EF 5 AddOrUpdate Duplicates data

余生颓废 提交于 2019-11-30 17:37:46

问题


This is the code in the Seed method:

var city = new City { Name = "A" };

var nh = new List<Neigh>
{
    new Neigh { City = city, Name = "N1" },
    new Neigh { City = city, Name = "N2" },
    new Neigh { City = city, Name = "N3" },
    //new Neigh { City = city, Name = "N4" },
};

context.Neighs.AddOrUpdate(
    p => p.Name,
    nh.ToArray()
);

After running update-database everything works as expected. I can run it multiple times without problem. However if at some point I uncomment the fourth neighborhood and run update-database again I end up with two records with city "A" and N4 is pointing to that city, while the rest point to the original city.

How do I prevent the inserting of a duplicate city if the list gets updated?


回答1:


You must start the script by checking whether the city already exists:

var city = context.Cities.FirstOrDefault(c => c.Name == "A") 
                                     ?? new City { Name = "A" };


来源:https://stackoverflow.com/questions/16851536/ef-5-addorupdate-duplicates-data

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