0
我有一個問題。在實體框架上使用流暢的api映射實體5
我有這兩個表:
主要表是用戶與顧客的依賴。
反向工程師第一代碼生成的類如下:
public class User
{
public User()
{
this.Customers = new List<Customer>();
}
...
public virtual ICollection<Customer> Customers { get; set; }
}
public class Customer
{
public Customer()
{
}
...
public int UserID { get; set; }
public virtual User User { get; set; }
}
我發在用戶類以下修改:
public class User
{
public User()
{
}
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
}
由於關係是1對零或 - 一。
原來的映射是這樣的:
// Relationships
this.HasRequired(t => t.User)
.WithMany(t => t.Customers)
.HasForeignKey(d => d.UserID);
而且修改後的映射是這樣的:
this.HasRequired(t => t.User)
.WithOptional(t => t.Customer)
.Map(m => m.MapKey("UserID"));
是正確的? 如果不是,這個映射將如何?
謝謝。
嗨@Slauma,我不明白爲什麼刪除customer表的外鍵。我在這個例子中做了他的第二個選擇。 – Gus
@格斯:不,這不是他的第二選擇。他的第二個選擇(「一對一外鍵協會」)使用'WithMany()',而不是'WithOptional'。這是與已移除集合的一對多關係,即只有一個導航屬性。另外,如果您有一個名爲UserID的屬性,則不能使用MapKey(「UserID」)。那麼你必須使用'HasForeignKey',就像Mortezza的例子所示。 – Slauma
嗨@Slauma,謝謝你的幫助。 – Gus