リスト「customersFromFile」に11,000人の顧客がいて、DBに8000人の顧客がいるとしましょう
以下のコードでは、EF が DB 内の既存の 8000 人の顧客を更新し、残りの 3000 人を DB に追加することを期待しています。
コンソールには、「Updated customers: 8000」および「Added to customers: 3000」が正しく出力されます。
ただし、DB には現在、合計 19000 の顧客がいますが、既存の 8000 は正常に更新されています。
これについて私を助けてください。
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();
更新 2: この回答に対して TomTom に感謝します。CustomerFromFile リストを作成するときに顧客をコンテキストに追加するという私の間違いです。これを発見するのに何時間もかかりました:(