簡體   English   中英

實體框架代碼優先的一對一關系

[英]Entity Framework Code-First One-To-One Relationship

我有兩個數據庫表:

顧客

  • 客戶編號(PK)
  • 名稱
  • ...

客戶設置

  • 客戶編號(PK)
  • 設置1
  • 設置2
  • ...

是否有可能使用代碼優先的類? 如果是這樣,流利的映射是什么?

public class Customer
{
    public int CustomerId { get; set; }
    public int Name { get; set; }
    public CustomerSetting CustomerSetting { get; set; }
}

public class CustomerSetting
{
    public int CustomerId { get; set; }
    public int Setting1 { get; set; }
    public int Setting2 { get; set; }
    public Customer Customer { get; set; }
}

我個人不喜歡一對一的桌子。 畢竟,為什么不只將設置列添加到客戶表? 不幸的是,這是我需要發展的。 對於這種情況,我無法找到正確的代碼優先映射。 謝謝你的幫助。

如果您首先要編寫代碼,並且想同時擁有Customer和CustomerSettings類,但是如您的文章所建議的那樣,則只具有這兩個表,則我將使用復雜的類型。 在這里看到一個很好的例子:

http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx

因此,您的對象模型應如下所示(我尚未對其進行測試):

public class Customer
{
    public Customer()
    {
        CustomerSetting= new CustomerSetting();
    }

    public int CustomerId { get; set; }
    public int Name { get; set; }
    public CustomerSetting CustomerSetting { get; set; }
}

[ComplexType]
public class CustomerSetting
{
    public int CustomerId { get; set; }
    public int Setting1 { get; set; }
    public int Setting2 { get; set; }
    public Customer Customer { get; set; }
}

您的模型類是正確的,如果您願意,可以將其添加到模型構建器中以指定哪個表是“主表”:

.Entity<Customer>()
.HasOptional(c => c.CustomerSetting)
.WithRequired(u => u.Customer);

暫無
暫無

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

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