![](/img/trans.png)
[英]How can I do a dependent entity read only without losing the foreign key in EF core 2.0?
[英]How do I correctly update an entity with foreign key in EF?
我經歷了這個答案 ,但仍然給了我同樣的例外。 我的DbContext
具有Configuration.AudoDetectChangesEnabled = false
和Configuration.LazyLoadingEnabled = true
,以防有所不同。 對於一個簡單的示例,請考慮以下內容:
public class Employee {
public int Id {get;set;}
public int TitleId {get;set;}
[ForeignKey(nameof(Employee.TitleId))]
public virtual Title Title{get;set;}
}
使用Context.Set<Employee>().Include(nameof(Employee.Title))
。 在我的情況下,我有一個現有的Employee
和一個Title
。 我已經使用新的TitleId
更新了我的實體,該TitleId
已經存在於數據庫中。 然后,我將EntityState
更新為EntityState.Modified
並調用SaveChanges()
。 這給出了以下Exception
:
A referential integrity constraint violation occurred: The property value(s) of 'Employee.TitleId' on one end of a relationship do not match the property value(s) of 'Title.Id' on the other end.
好的,那應該是由於外鍵ID與Navigation屬性之間的不匹配。 因此,在設置EntityState
之前,我將Title
設置為null
。 還是一樣的問題。
接下來,我嘗試在設置EntityState.Modified
之前分離實體。 現在,保存該實體即可,但是當我嘗試再次加載它時,在導航屬性上得到了NullReferenceException
。
正確的方法是什么?
不要嘗試僅更新Id屬性,而是更新員工上的Title實體,然后應遵循Id屬性。 因此,從數據庫中獲取現有的標題和學生,然后將學生的標題設置為您從數據庫中獲取的標題。
我會做其他改變的其他事情是使用System.Data.Entity,並使用帶有lambda表達式的include來使其更加明確和故障安全。 像這樣:
Context.Set<Employee>().Include(x => x.Title);
如果我沒看錯,在這種情況下,因為EF約定始終會映射到相同的名稱,所以您的ForeignKey注釋已過時。 我還認為在實體上具有映射信息有點代碼味道。 請改用流利的api。 http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.