Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# EF Code First Seeding Data - Keeps Adding (Instead of updating) [duplicate]

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));
like image 603
scniro Avatar asked Oct 29 '25 01:10

scniro


1 Answers

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" }
);
like image 194
ledgeJumper Avatar answered Nov 01 '25 01:11

ledgeJumper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!