实体框架代码优先一对一关系

时间:2013-06-18 16:06:53

标签: entity-framework ef-code-first

我有两个数据库表:

客户

  • CustomerId(PK)
  • 名称
  • ...

CustomerSettings

  • CustomerId(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; }
}

我个人不喜欢一对一的桌子。毕竟,为什么不将设置列添加到客户表?不幸的是,这是我需要开发的。我无法为这种情况找出正确的代码优先映射。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

如果您要先获取代码并希望同时拥有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; }
}

答案 1 :(得分:0)

您的模型类是正确的,如果您需要,可以将其添加到模型构建器以指定哪个表是“主要的”:

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