Create a list of PurchaseSaleLog, then before saving using the debugger inspect values to ensure each element in the list is not a duplicate. Finally use AddRangeAsync to perform the add new records.
Why is EF core 5.0 inserting duplicate records ?
Waqar Mehmood
1
Reputation point
Why is Entity Framework 5.0 inserting duplicate records in the Database in uncertain behavior when using AddAsync() method for adding data.
2 answers
Sort by: Most helpful
-
-
Karen Payne MVP 35,196 Reputation points
2022-06-10T10:59:29.64+00:00 Here is a conceptual example for working with AddRange (works with AddRangeAsync also).
DeviceType
is a reference table used in other models. Yes it's not a for statement either but that does not matter. The point is we can set a breakpoint right before the SaveChanges and inspect data in the list which you would do outside the for statement before the save.After the save all added items will have a key.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using RelationalLevel1.Data; using RelationalLevel1.Models; namespace RelationalLevel1.Classes { public class PopulateOperations { public static async Task People() { List<DeviceType> deviceTypes = new() { new() { Description = "Home phone" }, new() { Description = "Work phone" }, new() { Description = "Home email" }, new() { Description = "Work email" } }; List<Person> people = new List<Person> { new () { FirstName = "Karen", LastName = "Payne", Addresses = new List<Address>() { new () {Street = "123 Maple Street", PostalCode = "00022"}, new () {Street = "222 Apple street", PostalCode = "00022"}, }, ContactDevices = new List<ContactDevice>() { new () {DeviceTypeId = 1, Value = "503 999-1111"}, new () {DeviceTypeId = 3, Value = "karenp@gmail.com"} } }, new () { FirstName = "Mary", LastName = "Jones", Addresses = new List<Address>() { new () {Street = "123 Cherry Street", PostalCode = "99999"}, new () {Street = "222 High Lane", PostalCode = "67654"}, new () {Street = "444 Birch Ave", PostalCode = "98234"}, }, ContactDevices = new List<ContactDevice>() { new () {DeviceTypeId = 1, Value = "503 555-5151"}, new () {DeviceTypeId = 3, Value = "mary@work.net"}, new () {DeviceTypeId = 2, Value = "971-987-9832"} } } }; await using var context = new PersonContext(); context.AddRange(deviceTypes); context.AddRange(people); await context.SaveChangesAsync(); } } }