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

时间:2014-05-14 16:30:08

标签: c# asp.net-mvc entity-framework orm table-per-type

我有一个与this question非常相似的场景,但我想尝试更复杂的事情。

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

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

基本上,如果对象层次结构设置正确并且导航属性(和集合)都具有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(对于his answer here的@Ladislav的信用)。

相关问题