子和根聚合之间的映射

时间:2014-03-05 12:13:32

标签: c# ef-code-first entity-framework-6

我正在尝试为旧数据库创建EF CodeFirst映射。

让我们说我得到了以下课程:

public class Subscriber
{
    public Guid Id { get; set; }
    public SubscriberAddress Address { get; set; }
}

public class SubscriberAddress
{
    //[...]
}

我想在它们之间配置映射。表格如下:

create table Subscriber
(
    Id uniqueidentifier primary key,
    -- [...]
)

create table SubscriberAddress
(
    SubscriberId uniqueidentifier,
    -- [...]
)

所以关系在SubscriberAddress表中,但在类中我希望地址是Subscriber类中的属性。

我尝试使用WithRequiredPrincipalWithRequiredDependent,但无法理解如何进行映射,因为FK位于另一个表中。

修改

SubscriberAddress没有引用Subscriber的属性,Subscriber.Address是可选的。

1 个答案:

答案 0 :(得分:1)

假设它是一对一的关系并且两者都是必需的,那么这应该有用。

public class SubscriberContext : DbContext
{
    public DbSet<Subscriber> Subscribers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Entity<Subscriber>().HasRequired(x => x.Address).WithRequiredPrincipal(x => x.Subscriber);
        modelBuilder.Entity<Subscriber>().HasOptional(x => x.Address).WithRequired(x => x.Subscriber);
        modelBuilder.Entity<SubscriberAddress>().Property(x => x.Id).HasColumnName("SubscriberId");
        base.OnModelCreating(modelBuilder);
    }
}

public class Subscriber
{
    public Guid Id { get; set; }
    public virtual SubscriberAddress Address { get; set; }
}

public class SubscriberAddress
{
    public Guid Id { get; set; }
    public virtual Subscriber Subscriber { get; set; }
}