我正在尝试为旧数据库创建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
类中的属性。
我尝试使用WithRequiredPrincipal
和WithRequiredDependent
,但无法理解如何进行映射,因为FK位于另一个表中。
修改
SubscriberAddress
没有引用Subscriber
的属性,Subscriber.Address
是可选的。
答案 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; }
}