将Entity Framework中的表拆分为多个实体

时间:2013-07-23 18:49:20

标签: c# entity-framework entity-framework-5

这是问题所在。我有表用户,其中有很多字段。我想要做的是将此表拆分为多个实体,如下所示:

User
  -> GeneralDetails
  -> CommunicationDetails
  -> Address

etc.

用户中将某些字段提取到 GeneralDetails 时,一切顺利。但是,当我尝试为 CommunicationDetails 做同样的事情时,EF会爆炸并要求在 GeneralDetails CommunicationDetails 之间建立一对一的关系

样本实体定义:

public class User {
    public int UserId { get; set; }

    public string SomeField1 { get; set; }
    public int SomeField2 { get; set; }

    public virtual GeneralDetails GeneralDetails { get; set; }
    public virtual CommunicationDetails CommunicationDetails { get; set; }
    public virtual Address Address { get; set; }
}

public class GeneralDetails {   
    [Key]
    public int UserId { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    public virtual User User { get;set; }
}

public class CommunicationDetails { 
    [Key]
    public int UserId { get; set; }

    public string Phone { get; set; }
    public string DeviceToken { get; set; }

    public virtual User User { get;set; }
}

public class Address {  
    [Key]
    public int UserId { get; set; }

    public string City { get; set; }
    public string Country { get; set; }
    public string Street { get; set; }

    public virtual User User { get;set; }
}

样本映射:

modelBuilder.Entity<User>().
             HasRequired(user => user.GeneralDetails).
             WithRequiredPrincipal(details => details.User);

modelBuilder.Entity<User>().
             HasRequired(user => user.CommunicationDetails).
             WithRequiredPrincipal(details => details.User);

modelBuilder.Entity<User>().
             HasRequired(user => user.Address).
             WithRequiredPrincipal(details => details.User);

modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<GeneralDetails>().ToTable("Users");
modelBuilder.Entity<Address>().ToTable("Users");

为什么地球上EF想要这种关系?有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

实际执行此操作的正确方法是使用复杂类型而非实体。它实际上是一个比你想象的更常见的问题。

public class MyDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelbuilder.ComplexType<CommunicationDetails>();
        modelbuilder.ComplexType<GeneralDetails>();
        modelbuilder.ComplexType<Address>();
        modelbuilder.Entity<User>().ToTable("Users");
    }
}