简体   繁体   English

C#实体框架插入而不是更新

[英]C# Entity Framework inserts instead of update

Let say I have a 11,000 customers in the list 'customersFromFile' and 8000 customers in DB 假设我在“ customersFromFile”列表中有11,000个客户,在数据库中有8000个客户

With the code below, I expect EF will update the existing 8000 customers in DB, and add 3000 left to DB 使用下面的代码,我希望EF将更新DB中现有的8000个客户,并向DB中增加3000个

The console are printed correctly with "Updated customers: 8000" and "Added to customers: 3000 控制台已正确打印“更新的客户:8000”和“添加到客户:3000

However in DB now I have total 19000 customers although the existing 8000 are updated successfully. 但是,在DB中,尽管现有8000个已成功更新,但我总共有19000个客户。

Please help me on this. 请帮我。

DEMOEntities context = new DEMOEntities();
context.Configuration.AutoDetectChangesEnabled = false;
context.Configuration.ValidateOnSaveEnabled = false;

int i = 0;
foreach (var customerInDB in context.Customers)
{
    //Console.WriteLine("Update customer: " + customerInDB.CustomerID.ToString());
    customerInDB.Name = customersFromFile[i].Name;
    customerInDB.CIC = customersFromFile[i].CIC;
    customerInDB.IndustryCode = customersFromFile[i].IndustryCode;
    context.Entry(customerInDB).State = EntityState.Modified;
    i++;
}

Console.WriteLine("Updated customers: " + i.ToString());

int j = 0;
for (; i < customersFromFile.Count; i++)
{
    context.Customers.Add(customersFromFile[i]);
    j++;
}
Console.WriteLine("Added to customer:" + j.ToString());    

Console.WriteLine("Saving changes to customer...");
context.SaveChanges();

Update 2: Thanks TomTom for this answer, my mistake to add customer to context when I form up the CustomerFromFile List. 更新2:感谢TomTom的回答,这是我在形成CustomerFromFile列表时将客户添加到上下文中的错误。 It took me hours to discover this :( 我花了几个小时才发现这个:(

This sounds like you have no unique identifier for your customers. 听起来您没有客户的唯一标识符。

In the second loop, you should check if the 'customer from file' isn't already in DB before adding it (probably basically same Name, same CIC and same IndustryCode). 在第二个循环中,应在添加文件之前检查“文件中的客户”是否不在数据库中(可能基本上是相同的名称,相同的CIC和相同的IndustryCode)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM