0

我目前正在使用 EF Core 2.2.1 和代码优先迁移将现有数据库设计迁移到新应用程序中。我们当前的设计有一个主表,然后可以有多个具有相同共享主键的子表。我看过这个类似的问题,并试图在那里复制答案,但在结果中显示数据时运气不佳。

简化的模式看起来有点像下面:

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; }
}

然后我使用fluent 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对象?这是 EF 所做的优化,我需要按需加载还是我错误地设置了关系?或者,我的方法在这里是否错误,我应该以不同的方式做这件事?A12A

4

1 回答 1

2

在 Entity Framework Core 中,虚拟导航属性不会自动加载,除非您配置延迟加载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,TypeCTypeD与之关联。

于 2019-01-22T12:31:38.923 回答