簡體   English   中英

如何與Entity Framework Code First建立一對一的關系

[英]How do I establish a one to one relationship with Entity Framework Code First

我一直在閱讀有關在EF中建立一對一關系的人的所有Google和SO頁面,但這對我不起作用。

這是我的模型:

帳戶:

public int Id {get; set;}
public virtual AccountConfig AccountConfig {get; set;}

帳戶地圖:

HasKey(t => t.Id);
HasRequired(t => t.AccountConfig)
    .WithOptional();

帳戶配置:

public int Id {get; set;}
public int AccountId {get; set;}
public virtual Account Account {get; set;}

帳戶配置圖:

HasKey(t => t.Id);
HasRequired(t => t.Account)
    .WithOptional(t => t.AccountConfig);

在執行時, AccountConfig財產AccountNULLAccount上的財產AccountConfig是不正確的記錄(巧合的是,檢索Account.Id是一樣的AccountConfig.Id ,但我不知道這意味着什么)。

在數據庫中, Account表沒有對AccountConfig記錄的引用,但AccountConfig表使用AccountId列引用了Account記錄。

最終結果是我可以從Account引用AccountConfig ,並且(如果可能的話)引用AccountConfig Account

使用EF,僅在共享主鍵的表上支持一對一關系。 您的AccountConfig表具有自己的主鍵和Account的外鍵。 EF僅支持與此配置的一對多關系。

本文對EF中的1:1和1:0..1關系進行了很好的解釋。 這里的限制是EF不支持唯一約束這一事實的副產品。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM