C#EF代码第一播种数据 - 继续添加(而不是更新)

时间:2013-09-27 19:09:40

标签: c# entity-framework ef-migrations

我有一个User类型的列表,当我尝试播放我的数据库以反映更新时,它只是再次添加所有条目。我将分享我在Seed()方法中执行的代码。我希望只更新记录(但保留添加功能),如果它们已经存在。有什么想法吗?

List<User> users = new List<User>();

users.Add(new User { FirstName = "Dee", LastName = "Reynolds" });
users.Add(new User { FirstName = "Rickety", LastName = "Cricket" });

users.ForEach(b => context.Users.AddOrUpdate(b));

2 个答案:

答案 0 :(得分:7)

您只需在添加/更新记录时指定要检查的密钥。因此,对于新用户,您可以这样做:

context.Users.AddOrUpdate(x => x.UserName, //Or some other field that you know will be consistant
    new User { FirstName = "Dee", LastName = "Reynolds" }
);

答案 1 :(得分:0)

修改AddOrUpdate方法以指定要检查的属性并查看该行是否已存在:

users.ForEach(b => context.Users.AddOrUpdate(c => c.LastName, b));

了解更多信息:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application