1

當我創建一個新的EF對象時,我首先將它附加到DbSet,然後將其導航屬性之一設置爲不同EF對象的新實例。然後我將第一個EF添加到DbSet並調用保存。我得到以下異常:實體框架InvalidOperationException保存

System.InvalidOperationException: The changes to the database were committed 
successfully, but an error occurred while updating the object context. The 
ObjectContext might be in an inconsistent state. Inner exception message: A 
referential integrity constraint violation occurred: The property value(s) of 
'Location.Id' on one end of a relationship do not match the property value(s) 
of 'Pool.LocationId' on the other end. 

這裏是我的代碼:

ORMContext context = new ORMContext(); 

var l = context.Locations.Create(); 
context.Locations.Attach(l); 
...set properties 
context.Locations.Add(l); 

var p = context.Pools.Create(); 
context.Pools.Attach(p); 
p.Location = l; 
...set properties 
context.Pools.Add(p); 

context.SaveChanges(); 

我認爲正在發生的是Location對象是新的和Id0默認。 EF正在更新Pool(設置爲0)的外鍵,然後在將Location對象保存到數據庫後更新Location.Id。因此Location.Id現在設置爲數據庫中的關聯值,如149,並且Pool.LocationId仍然設置爲0

如何避免此異常?或者我想如何處理它?

回答

2

您可以添加的位置,這樣的參考實體將被設置

ORMContext context = new ORMContext(); 

    var l = context.Locations.Create(); 
    context.Locations.Attach(l); 
    ...set properties 
    context.Locations.Add(l); 

    context.SaveChanges(); // save here, that way the location will get its Id 
    var p = context.Pools.Create(); 
    context.Pools.Attach(p); 
    p.Location = l; 
    ...set properties 
    context.Pools.Add(p); 

    context.SaveChanges(); 

這將是一個辦法

+0

同意後保存。這將解決問題。但是,這不是一個選項。然後它將保存任何其他更改,這些更改位於DbContext中,直到用戶在UI中選擇「保存」後才能強制執行。 –