简体   繁体   中英

writing Linq-to-Entities query

I am new to LINQ and Entity Framework and I am stuck on a particular query which I am trying to write. I have a database with the below structure. To keep it simple, I have just included the files and fields that are relevant to the problem.

Table: SCMPOFILE
Columns: 
POKEY
PONUMBER
...


Table: SCMSKUFILE
SKUKEY
POKEY - Foreign Key on SCMPOFILE.POKEY
.....


Table: SCMSHPMAST
SHIPKEY
DELIVERYDATE
.....


Table: SCMSHIPPINGDETAIL
SHPDTLKEY
SHIPKEY  - Foreign Key on SCMSHPMAST.SHIPKEY
POKEY - Foreign Key on SCMPOFILE.POKEY
SKUKEY - Foreign Key on SCMSKUFILE.SKUKEY
......

As you can see from the structure, 1 shipment Key can have multiple shipment Detail Keys Similarly, each PO and sku can have multiple Shipment Keys associated with it.

I am trying to find all skus (SCMSKUFILEs) where SCMSHPMAST.DELIVERYDATE is not null. As I have defined the foreign keys, the model generated automatically brings the SCMSHIPPINGDETAILs with each SCMSKUFILE associated to it (and SCMSHPMAST attached to each SCMSHIPPINGDETAIL). I can do joins on all the individual files to get my desired results, but I want to use the LINQ and the model generated by entity framework for that.

I am trying to do something like this:- Select all SCMSKUFILEs where SCMSHIPPINGDETAILs has SCMSHPMAST having DELIVERYDATE not equal to null.

Is this something which can be done using a single LINQ query? I have scratched my head a lot but I am not able to write the LINQ query.

I hope I have explained my problem properly. Please let me know if I have missed anything?

Thanks, Abhi.

Have you tried something like this?

var results = SCMSKUFILEs.Where(a => a.SCMSHIPPINGDETAILs.Any(d => d.SHIPMASTs.Any(m => m.DELIVERYDATE != null)));

Not sure off the top of my head if it'd work worth a damn with the nested ANY's, but worth a try.

You could also go from the other direction, something like this...

var results = SHIPMASTs.Where(m => m.DELIVERYDATE != null)
    .SelectMany(m => m.SCMSHIPPINGDETAILs)
    .SelectMany(d => d.SCMSKUFILEs)
    .Distinct();

Without looking too deeply into the structure of your tables, it appears that you are looking for a query that restricts parent results (SCMSKUFILE) based on the properties of some of their children (DELIVERYDATE not equal to null). LINQ uses quantifiers "Any" and "All" to express such queries, for example:

edm.Parents.Where(p => p.Children.Any(c => c.DeliveryDate != null));

This may not translate into the exact SQL query that you have in mind, but it should work.

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