0

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

User
  -> GeneralDetails
  -> CommunicationDetails
  -> Address

etc.

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

示例实体定义:

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到底为什么要这种关系?有什么办法可以解决这个问题吗?

4

1 回答 1

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");
    }
}
于 2013-07-24T03:33:38.350 回答