我有两个数据库表:
客户
CustomerSettings
是否可以使用代码优先使用这些类?如果是这样,那么流畅的映射是什么?
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; }
}
我个人不喜欢一对一的桌子。毕竟,为什么不将设置列添加到客户表?不幸的是,这是我需要开发的。我无法为这种情况找出正确的代码优先映射。谢谢你的帮助。
答案 0 :(得分:0)
如果您要先获取代码并希望同时拥有Customer和CustomerSettings类, 但正如你的帖子所暗示的那样,两者只有一张桌子, 我会使用复杂的类型。 在这里看到一个很好的例子:
所以,你的对象模型应该是这样的(我没有测试过它):
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);