3

我有一个类型列表,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));
4

2 回答 2

7

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

context.Users.AddOrUpdate(x => x.UserName, //Or some other field that you know will be consistant
    new User { FirstName = "Dee", LastName = "Reynolds" }
);
于 2013-10-01T16:34:09.713 回答
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-应用程序

于 2014-12-12T20:39:18.663 回答