繁体   English   中英

在每个类型继承方案的表中加载EF导航属性

[英]Load EF navigation property in a Table per Type Inheritance scenario

我有一个非常类似于此问题的方案,但我正在尝试更复杂的事情。

回顾一下,我基本上有一个案例列表,每个案例都有不同的类型:

Case -> CaseA
Case -> CaseB
Case -> CaseC

每个派生的Case类都有一个或多个导航属性,我需要包括:

Case -> CaseA -> Employee
Case -> CaseB -> List<Something>
Case -> CaseC -> List<SomethingElse>

现在,我当然可以执行大量的switch语句,但是我正在寻找类似以下的聪明的东西:

foreach(var myCase in ListOfCases) 
{
    context.LoadAll(myCase); // <- THIS!
    context.Entry(myCase).LoadAllProperties() // <- OR THIS...
    // etc. etc.
}

当然,这些方法不存在,所以我想知道是否有人遇到过类似的问题,什么是解决该问题的好方法。

谢谢!

最后,解决方案非常简单:什么都不做! :)

基本上,如果对象层次结构设置正确,并且导航属性(和集合)都具有virtual修饰符,以便可以启用LazyLoading ,则EF会自行跳入对象层次结构以加载在第一次SELECT期间未加载的属性:

 public CasesDbContext() {
     Configuration.LazyLoadingEnabled = true;
     Configuration.ProxyCreationEnabled = true;
 }

然后例如这是方法:

var result = new List<CaseViewModel>();
var cases = _casesRepository.All;
foreach (var customCase in cases) {
    result.Add(new CaseViewModel() {
        Complete = customCase.IsComplete(), // <- at this point, the customCase is
                                            // the derived implementation
                                            // but the full hierarchy is missing
    });
}

这是派生类的示例:

public class CaseB : Case {
    public int ReferenceId { get; set; }
    public virtual Reference Reference { get; set; } // <- "virtual" here is important!

    protected override bool IsComplete() {
        return Reference.Name == "Tallmaris"; // <- at this point the EF 
                                              // will load the Reference.
    }
}

另一个警告是,在遍历一组实体时加载引用可能会产生错误,例如There is already an open DataReader associated with this Command which must be closed first 解决方案是在迭代之前使用ToList()或在连接字符串中启用MultipleActiveResultSets此处提供对@Ladislav的感谢,以供参考)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM