EF 5 AddOrUpdate Duplicates data

2019-02-14 18:37发布

问题:

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()
);

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?

回答1:

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" };