我目前正在使用EF Core 2.2.1通过代码优先迁移将现有数据库设计迁移到新应用程序中。我们当前的设计有一个主表,然后可以有多个具有相同共享主键的子表。我看过this similar question并尝试在此处复制答案,但是在结果中显示数据并没有多大运气。
简化后的架构看起来类似于以下内容:
public class Root
{
public enum SubEntityType
{
A,
B,
C,
D
}
public Guid Id { get; set; }
public SubEntityType Type { get; set; }
public virtual TypeA A { get; set; }
public virtual TypeB B { get; set; }
public virtual TypeC C { get; set; }
public virtual TypeD D { get; set; }
}
public class TypeA
{
public Guid Id { get; set; }
public virtual Root Root { get; set; }
public int A { get; set; }
}
public class TypeB
{
public Guid Id { get; set; }
public virtual Root Root { get; set; }
public Guid B { get; set; }
}
public class TypeC
{
public Guid Id { get; set; }
public virtual Root Root { get; set; }
public string C { get; set; }
}
public class TypeD
{
public Guid Id { get; set; }
public virtual Root Root { get; set; }
public bool D { get; set; }
}
然后,我使用流利的api建立关系,如下所示:
builder.Entity<Models.Root>()
.HasOne( e => e.A )
.WithOne( e => e.Root )
.HasForeignKey<Models.TypeA>( e => e.Id );
builder.Entity<Models.Root>()
.HasOne( e => e.B )
.WithOne( e => e.Root )
.HasForeignKey<Models.TypeB>( e => e.Id );
builder.Entity<Models.Root>()
.HasOne( e => e.C )
.WithOne( e => e.Root )
.HasForeignKey<Models.TypeC>( e => e.Id );
builder.Entity<Models.Root>()
.HasOne( e => e.D )
.WithOne( e => e.Root )
.HasForeignKey<Models.TypeD>( e => e.Id );
在我尝试添加数据之前,它似乎工作得很好。我用一些伪数据创建根条目。在root
表中:
Id Type
6f0f24cf-fbd7-4b4d-8059-0810daaf5460 1
在TypeA
表中:
Id A
6f0f24cf-fbd7-4b4d-8059-0810daaf5460 12
一切都很好,看起来也不错。当我这样查询时:
var result = ctx.Root.First();
我得到以下结果(道歉的格式,试图使其更好一点):
Name Value
result {Test.Models.Root}
A null
B null
C null
D null
Id {6f0f24cf-fbd7-4b4d-8059-0810daaf5460}
Type B
是否不应该将A
设置为Test.Models.TypeA
的{{1}}对象来填充A
?这是EF所做的优化,我需要按需加载12
还是建立了错误的关系?或者,我的方法在这里是错误的,我应该以不同的方式来做吗?
答案 0 :(得分:2)
在Entity Framework Core中,除非您Configure Lazy Loading或将Eager Loading
与Include
一起使用,否则不会自动加载虚拟导航属性。
因此,请按以下方式编写查询:
var result = ctx.Root.Include(r => r.TypeA).Include(r => r.TypeB)
.Include(r => r.TypeC).Include(r => r.TypeD).FirstOrDefault();
现在Root
将具有TypeA
,TypeB
,TypeC
和TypeD
关联。