简体   繁体   中英

Entity Framework Correlated Sub-query

I would like to create this using Entity Framework. A list of new objects containing fields from the parent and fields from the most current child record. I would write the SQL as a correlated sub-query:

SELECT p.PolicyNumber, p.HomeState, pt.RevisionDate, pt.TranStatus
FROM dbo.Policy p
JOIN dbo.PolicyTran pt ON p.Id = pt.Policy_Id
AND pt.RevisionDate = (
    SELECT MAX(mpt.RevisionDate)
    FROM dbo.PolicyTran mpt
    WHERE p.Id = pt.Policy_Id
    )
WHERE p.HomeState = 'NY'

The context for Policy has navigation to the list of transactions (PolicyTran).

var query = context.Policies.Include(t => t.PolicyTransactions);

No matter what I try the Linq is incorrect or the SQL is incorrect. Time to call in the experts.

It's not pretty but I believe this gets you what you wanted.

var query = db.Policies
.Where(p => p.HomeState == "NY")
.Join(db.PolicyTrans,
    p => p.Id,
    t => t.Policy_Id,
    (p, t) => new { P = p, T = t.OrderBy(tr => tr.RevisionDate).First() })
.Select(g => new {
    PolicyNumber = g.P.PolicyNumber,
    HomeState = g.P.HomeState,
    TransStatus = g.P.TransStatus,
    RevisionDate = g.T.RevisionDate
});

This is one way although 2 separate db hits. You could prob embed the first statement into the second one but that is more complicated for me right now as I don't have a compiler to hand.

var maxRevisionDate = context.PolicyTran.Max(x => x.RevisionDate);

var results = context.Policies.Where(x => x.PolicyTran.RevisionDate == maxRevisionDate 
               && x.HomeState == "NY").Include("PolicyTran")

I have made assumptions that your entity names are the SAME as your database tables. The result of this is an IEnumerable of Policies and their corresponding PolicyTrans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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