实体框架 - 使用TPT设置加载子类实体

时间:2017-01-24 20:07:49

标签: c# entity-framework linq

我们的系统正在接收来自两个外部来源的输入(电话/网络提交)。

//  Table-Per-Type Hierarchy
public class Submission
{
    public int SubmissionId { get; set; }   // Primary Key
    public int? PersonId { get; set; }
    public int? CompanyId { get; set; }
    public long? EmployeeId { get; set; }
    public bool? Completed { get; set; }
    public string AbsenceReason { get; set; }
    public string AbsenceType { get; set; }
    public DateTime? AbsenceDate { get; set; }
}

public class CallSubmission : Submission
{
    public string CallerId { get; set; }
    public string PhoneNumber { get; set; }
    public DateTime? HangUp { get; set; }
    public DateTime? PickUp { get; set; }        
}

public class WebSubmission : Submission
{
    public string EmailAddress { get; set; }
    public string PhoneNumber { get; set; }
    public DateTime SubmissionDate { get; set; }
}

我的目标是使用 PickUp / SubmissionDate 检索过去七天内的所有提交内容,具体取决于我们正在处理的提交类型。是否可以使用单个LINQ语句实现此目的?理想情况下,我希望避免在内存中加载两个不同的数据集。

我希望整合的声明

Users.Where(user => user.UserName == name)
     .SelectMany(user => user.Submissions)
     .OfType<CallSubmission)()
     .Where(call => call.PickUp >= startDate)

Users.Where(user => user.UserName == name)
     .SelectMany(user => user.Submissions)
     .OfType<WebSubmission>()
     .Where(web => web.SubmissionDate >= startDate)

1 个答案:

答案 0 :(得分:1)

实际上(令我惊讶的是)你问的是什么(至少在最新的EF6.1.3中),因为支持C#isas运算符(它们基本上被{{{ 1}}方法)。

OfType

重要的一部分是使用var query = db.Users .Where(user => user.UserName == name) .SelectMany(user => user.Submissions) .Where(subm => (subm as CallSubmission).PickUp >= startDate || (subm as WebSubmission).SubmissionDate >= startDate); 运算符而非as生成不受支持的异常。无需检查cast,因为生成的SQL查询自然会处理null