使用复杂类型的Entity Framework和Fluent API

时间:2012-04-06 14:00:47

标签: entity-framework fluent complextype

我正在使用Entity Framework 4.3 Code-FIrst创建一个新的数据库模型;使用Fluent API。虚拟模型如下。

所以我的主要对象是Something,我需要跟踪这个。所有其他项目都是免费的。通常在数据库中,我会分配一个表,例如Contact,主键和关系的foregin键。但是,阅读有关Fluent API和Complex Types的更多信息,尤其是this article,我注意到(我认为)我可以让EF负责链接这些对象/表格而我不需要担心他们在我的MVC应用程序中作为存储库。

请注意:

  • 联系
  • 的东西有一对多
  • 联系人有一对多地址
  • 与PhoenNumber联系有一对多

知道这一点,我的困惑在于复杂类型,因为联系人是Somethign和Address& amp;的完整类型。 PhoneNumber是某种复杂的类型。

  • 如何在Fluent API中设置此关系?
  • 我怎么说地址是必需的?
  • 在ASP.NET MVC中使用域驱动开发,我是否必须维护IContactRepository和IAddressRepository的存储库以推送到控制器?

(请注意,为简洁起见,省略了一些代码。)

// attempt
void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.ComplexType<Contact>();

    modelBuilder.ComplexType<Contact>().Property(p => p.Address).IsRequired();  // COMPILER ERROR

    modelBuilder.ComplexType<Address>();
    modelBuilder.ComplexType<PhoneNumber>();    
}


// DUMMY MODEL
class Something()
{
    void Something()
    {
        this.Contact = new HashSet<Contact>( );
    }

    DateTime DOB { get; set; }
    int YearsEmployed { get; set; }
    ICollection<Contact> Contact { get; set; }
}

class Contact()
{
    void Contact()
    {
        this.Address = new HashSet<Address>();
    }

    ICollection<Address> Address { get; set; }
}

class Address()
{
        string Street1 { get; set; }
        string Street2 { get; set; }
        string State { get; set; }
        string City { get; set; }
        string Zip { get; set; }
        OptionName OptionName { get; set; }
}

class PhoneNumber()
{
    string Number
    OptionName OptionName { get; set; }
}

class OptionName()
{
    string OptionName { get; set; }
}

1 个答案:

答案 0 :(得分:6)

没有一个类是复杂的类型。 Complex types必须遵守严格的规定。它们不能包含导航属性,并且因为它们映射到拥有实体的表,所以它们不能以与拥有实体的一对一关系的任何其他形式表示。

相关问题