I got this error when trying to seed data to the database
“The instance of entity type ‘Unit’ cannot be tracked because another instance with the same key value for {‘UnitId’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attach…”
This is the function call in program.cs:
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<DBContext>();
dbContext.Database.EnsureCreated();
SeedData.Seed(dbContext);
}
And here is the code to seed the data:
namespace cuahangbanle.DBData.Seed
{
public static class SeedData
{
public static void Seed(DBContext dbContext)
{
if (!dbContext.Roles.Any())
{
dbContext.Roles.Add(new Role { RoleId = "Admin", RoleName = "Administrator" });
}
dbContext.SaveChanges();
if (!dbContext.Accounts.Any())
{
dbContext.Accounts.Add(new Account
{
AccountId = "ACC001",
Username = "admin",
Password = "admin",
RoleId = "Admin",
});
}
dbContext.SaveChanges();
if (!dbContext.Suppliers.Any())
{
dbContext.Suppliers.AddRange(
new Supplier { SupplierId = "SUP001", SupplierName = "Supplier 1", CreatedBy = "ACC001" },
new Supplier { SupplierId = "SUP002", SupplierName = "Supplier 2", CreatedBy = "ACC001" }
);
}
dbContext.SaveChanges();
if (!dbContext.Units.Any())
{
dbContext.Units.AddRange(
new Unit { UnitId = "can", SmallUnit = "can", LargeUnit = "box" },
new Unit { UnitId = "package", SmallUnit = "package", LargeUnit = "box" }
);
}
dbContext.SaveChanges();
if (!dbContext.Categories.Any())
{
dbContext.Categories.AddRange(
new Category { CategoryId = "CAT001", CategoryName = "Category 1", CreatedDate = DateTime.Now, CreatedBy = "ACC001" },
new Category { CategoryId = "CAT002", CategoryName = "Category 2", CreatedDate = DateTime.Now, CreatedBy = "ACC001" }
);
}
dbContext.SaveChanges();
if (!dbContext.Products.Any())
{
try
{
dbContext.Products.AddRange(
new Product { ProductId = "PRD001", ProductName = "Coca", CategoryId = "CAT001", SupplierId = "SUP001", SupplierName = "Supplier 1", UnitId = "can", PurchasePrice = 7000, SalePrice = 8000, ProfitMargin = 14.29M, Profit = 1000, Stock = 10 },
new Product { ProductId = "PRD002", ProductName = "Hao Hao spicy noodles", CategoryId = "CAT002", SupplierId = "SUP002", SupplierName = "Supplier 2", UnitId = "package", PurchasePrice = 3000, SalePrice = 4000, ProfitMargin = 33.33M, Profit = 1000, Stock = 20 }
);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
dbContext.SaveChanges();
}
}
}
The error part goes here:
try
{
dbContext.Products.AddRange(
new Product { ProductId = "PRD001", ProductName = "Coca", CategoryId = "CAT001", SupplierId = "SUP001", SupplierName = "Supplier 1", UnitId = "can", PurchasePrice = 7000, SalePrice = 8000, ProfitMargin = 14.29M, Profit = 1000, Stock = 10 },
new Product { ProductId = "PRD002", ProductName = "Hao Hao spicy noodles", CategoryId = "CAT002", SupplierId = "SUP002", SupplierName = "Supplier 2", UnitId = "package", PurchasePrice = 3000, SalePrice = 4000, ProfitMargin = 33.33M, Profit = 1000, Stock = 20 }
);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
How should I fix this error?
10
The correct answer was provided by JasonPan above. Allow me to summarize as follows: change the method from void to async Task, replace all dbContext.SaveChanges() with await dbContext.SaveChangesAsync(), add await in front of the data seeding method calls. And finally, add MultipleActiveResultSets=True to your connection string. For example, in my case:
"ConnectionStrings": {
"DefaultConnection": "Data Source =.;Initial Catalog=demostore;Integrated Security=True;TrustServerCertificate=True;MultipleActiveResultSets=True"
},