EF 5 AddOrUpdate复制数据 [英] EF 5 AddOrUpdate Duplicates data
本文介绍了EF 5 AddOrUpdate复制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是Seed方法中的代码:
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()
);
在运行更新数据库后,一切正常。我可以多次运行它,而不会出现问题。但是,如果在某个时候取消注释第四个邻域并再次运行update-database,我最终会得到两个记录,其中城市为 A,N4指向该城市,其余的则指向原始城市。
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?
推荐答案
您必须通过检查城市是否已经存在来启动脚本:
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" };
这篇关于EF 5 AddOrUpdate复制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文