我發現的大多數問題都不是我正在尋找的類型。實體框架兩端可選1對1關係
我有2個表:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public Guid? CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerId { get; set; }
public Guid? UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
}
甲User
罐存在而不被一個Customer
和Customer
而不一個User
可以存在。
我試過這樣流暢的API:
modelBuilder.Entity<Customer>()
.HasOptional<User>(c => c.User)
.WithOptionalDependent(c => c.Customer)
.Map(c => c.MapKey("UserId"));
但它不斷給我這個錯誤,當我嘗試創建遷移:
Customer_User_Source: : Multiplicity is not valid in Role 'Customer_User_Source' in relationship 'Customer_User'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
更新
我將我的模型更改爲:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerId { get; set; }
public virtual User User { get; set; }
}
隨着流利的API:
modelBuilder
.Entity<Customer>()
.HasOptional(l => l.User)
.WithOptionalPrincipal()
.Map(k => k.MapKey("CustomerId"));
modelBuilder
.Entity<User>()
.HasOptional(c => c.Customer)
.WithOptionalPrincipal()
.Map(k => k.MapKey("UserId"));
這似乎是工作,但有沒有辦法來定義的,而不必使用MapKey
在模型中的列?
感謝第二個鏈接指出我正確的方向,你也許有我的編輯答案? – YesMan85
您是否看到編輯過的答案? – rlartiga
我讀過呀。我認爲這是EF實施的罪魁禍首。我首先創建了表模型,然後從中生成代碼。 EF實際上使它成爲1 .. *關係而不是1..1關係。 – YesMan85