Example for LINQ to Entities query with multi level relationship (grandparent / grandchild records)

Hi All,
Hoping there's a good LINQ coder that can help me out here. My database has a string of related tables where table B has a foreign key to table A and table C has foreign key to table B and table D has foreign key to table C. I need to write a LINQ to Entities query that looks something like:

var query = from d in entities.D where d.c.b.a.primarykey = x select d.textfield;

I don't seem to have grip on how to reach that far through the relationships to filter on a value.

Thanks
LVL 1
danburyitAsked:
Who is Participating?
 
danburyitConnect With a Mentor Author Commented:
I found a solution. (I'll post in case it helps anyone else. I'm just starting to get the hang of this LINQ stuff.) I changed object names to make it simple and generic (and match my question.)

Just to reiterate a bit: A table has a child table B (B has foreign keys to A). B table has a child table C. C has a child table D. (It's just a 4 table parent/child heirarchy chain.) I need to return a distinct list of D.PrimaryKey and D.TextField values where A.PrimaryKey = x.

(Thanks for looking)
            using (myEntities ent = new myEntities())
            {
                ObjectQuery<Dtable> dTable = ent.Dtable;
                ObjectQuery<Ctable> cTable = ent.Ctable;
 
                var query = (from d in dTable
                             from c in cTable
                             where d.DprimaryKey == c.d.DprimaryKey &&
                             c.b.a.AprimaryKey == x &&
                             d.TextField.Length > 0
                             select new { Key = d.DprimaryKey, Value = d.TextField }).Distinct();

Open in new window

0
 
Fernando SotoRetiredCommented:
Can you provide a UML type diagram of how the tables are set up Primary Key / Foreign Key and Relationships to see if I may be able to help you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.