实体框架6中的复杂子查询

时间:2016-10-12 09:12:41

标签: entity-framework

我有一个名为Insurance的实体,如下所示:

public class Insurance : BaseEntity, IExpirationDocument
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override int Id { get; set; }

    [Column(TypeName = "NVARCHAR")]
    [StringLength(256)]
    public string PathToCertificate { get; set; }

    [Column(TypeName = "NVARCHAR")]
    [StringLength(50)]
    public string Filename { get; set; }

    public int Value { get; set; }
    public string Name => InsuranceType.Name;
    public DateTime ExpiryDate { get; set; }
    public DateTime IssueDate { get; set; }
    public bool Active { get; set; }
    public int InsuranceTypeId { get; set; }
    public virtual InsuranceType InsuranceType { get; set; }
    public int InsurerId { get; set; }
    public virtual Insurer Insurer { get; set; }
    public int ApplicantId { get; set; }
    public virtual Applicant Applicant { get; set; }
    public int? DocumentEmailHistoryId { get; set; }
    public virtual DocumentEmailHistory DocumentEmailHistory { get; set; }

    public Insurance()
    {
        Active = true;
    }
}

是否可以使用Entity Framework执行此类查询:

SELECT * 
FROM Insurances i1
INNER JOIN 
    (SELECT 
         insuranceTypeId, applicantid, MAX(IssueDate) as 'maxissuedate'
     FROM 
         Insurances
     GROUP BY 
         insuranceTypeId, applicantid) AS i2 ON i1.applicantid = i2.applicantid
                                             AND i1.insuranceTypeId = i2.insuranceTypeId
WHERE 
    i1.issueDate = i2.maxissuedate

1 个答案:

答案 0 :(得分:1)

如果您尝试根据InsuranceInsuranceTypeId获取最新发布的 ApplicantId,您可以根据需要的属性对数据进行分组,请按{{1}排序降序并只获取一个IssueDate信息。当然它不会给你相同的查询,但它会给你相同的结果

Insurance