【问题标题】:Maintain relationship in derived type in EF Core在 EF Core 中维护派生类型的关系
【发布时间】:2019-03-20 05:26:11
【问题描述】:

我在维护派生类型中的关系并使用 LINQ 查询它们时遇到了一些问题。请考虑以下情况。假设我有以下层次结构:

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public abstract class Document
{
    public int Id { get; set; }
    public string DocType { get; set; }
    public string Name { get; set; }
}

public class CompanyDoc : Document
{
    public int CompanyId { get; set; }
    public Company Company { get; set; }
}

public class PersonDoc : Document
{
    public int PersonId { get; set; }
    public Person Person { get; set; }
}

这意味着我有一个文档对象,并且文档的所有者可以是任何公司或任何人,因此我创建了 2 个派生文档公司文档和个人文档。

我的问题是,以这种方式维持关系是否可以,如果不能,那么维持这种层次结构的最佳方法是什么?

在 ef core 2.1 中,我可以使用 TPH 处理此层次结构。但是,如果我想连同所有者一起获取所有文档,那么 linq 查询将是什么。我尝试过以下一种,但它不起作用。

var doc = (from d in _context.Set<Document>()
            join c in _context.Company on (d as CompanyDoc).CompanyId equals c.Id into cd
            from cdoc in cd.DefaultIfEmpty()
            join c in _context.Person on (d as PersonDoc).PersonId equals c.Id into pd
            from pdoc in pd.DefaultIfEmpty()
            select new {
                d.Id,
                d.Name,
                Owner = cdoc.Name != null ? cdoc.Name : pdoc.Name
            }).ToList()

你能帮我分享你的想法吗?请将此作为假设示例。

【问题讨论】:

    标签: c# asp.net-core ef-core-2.1 ef-core-2.2 entity-framework-core-2.1


    【解决方案1】:

    我认为您使查询过于复杂。 EF Core 在处理每个层次结构表 (TPH) 查询方面非常聪明。通过使用抽象类作为DbSet&lt;T&gt; 属性,您可以访问所有类型,并过滤掉您想要的。

    因此,在您的示例中,DbContext 将包含一个属性 public DbSet&lt;Document&gt; Documents { get ; set; },并且以下查询将起作用。

    //This returns all the documents - each document is of the correct type
    //e.g PersonDocument or CompanyDocument
    var allDocs = context.Documents.ToList();
    
    //This would only return PersonDocuments - change the type for other versions
    var personDocs = context.Documents.OfType<PersonDocument>().ToList();
    

    EF Core 竭尽全力为您获取正确的数据和类型。很好用。

    PS。如果你有我的书Entity Framework Core in Action,那么我会在第 7.8.2 节,尤其是第 201 页介绍 TPH。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2010-10-08
      相关资源
      最近更新 更多