2013-06-18 112 views
1

我有两个数据库表:实体框架代码优先一比一的关系

客户

  • 客户ID(PK)
  • 名称
  • ...

CustomerSettings

  • 客户ID(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; } 
} 

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

+0

一种可能的情况。虽然这是不适合你的情况。我已经在我的答案中提出了解决方案。 –

+0

听起来像别人正在口述数据模型。在这种情况下,首先选择模型或首先选择Db是比代码优先选择更好的选择。 – Maess

回答

0

如果你是第一次去的代码,并希望有客户和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; } 
} 
+0

对不起,我的帖子建议需要两张桌子。我在旁边说我不会使用两个表来设计我的数据库,但不幸的是,我无权改变现有的两个表结构。 –

+0

在这种情况下,我同意@Maess,如果你已经拥有数据库,那么模型首先是要走的路,而不是第一个。 –

0

你的模型类新是正确的,如果你想你可以添加到您的模型生成指定哪个表是“主一”:用PK与FK到anoter PK是inhertience

.Entity<Customer>() 
.HasOptional(c => c.CustomerSetting) 
.WithRequired(u => u.Customer); 
相关问题