4

I have a list of type User and when I try to seed my db to reflect updates, it is simply adding all the entries again. I will share my code I am executing in my Seed() method. I wish to just update the records (but keep the add functionality), if they already exist. Any thoughts?

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));
scniro
  • 16,844
  • 8
  • 62
  • 106
  • 1
    This is not working because `EF` is comparing on some field (probably id) that you are not populating. You might try `.Attach(b)` if you already know they exist. – crthompson Sep 27 '13 at 19:14
  • I can not implement another meaning to b with the current structure. Slightly different scenario than provided question – scniro Sep 27 '13 at 19:24
  • It is possible I will not know if object exists or not. I wish to edit if so, or add if not. – scniro Sep 27 '13 at 19:28
  • This is a question that gets asked a lot. http://stackoverflow.com/a/17719137/150342. Take care..http://thedatafarm.com/blog/data-access/take-care-with-ef-4-3-addorupdate-method/ – Colin Sep 28 '13 at 21:44

2 Answers2

7

You simply need to specify the key you want to check against when you are adding/updating the record. So for a new User you would do this:

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

Modify your AddOrUpdate method to specify a property to checked and see if the row already exists:

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

For more info: 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

crgeee
  • 1
  • 1