Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with LINQ to SQL WHERE-clause on foreign table

Let's say I have these two tables:

ParentDataItem
    ParentDataItemID
    ...some other fields...

ChildDataItem
    ChildDataItemID
    ParentDataItemID (foreign key)
    Name
    Value

Now I want to select any ParentDataItems that have a ChildDataItem with a specified name and value.

I know I was way off with my first approach, which was something like:

// db is the data context object
db.ParentDataItems.Where(p => p.ChildDataItems.Where(c => c.Name == "XXX" && c.Value == "XXX"));

I prefer lambda syntax but either would do.

like image 941
jhorback Avatar asked Nov 26 '25 18:11

jhorback


2 Answers

If there's already a relationship between them (because you set one up in the designer for example) you should just be able to do:

var foo = db.ParentDataItems.Where(p => p.ChildDataItems.Any(c => c.Name == "value");

Which will get any parent data items that have any children with a name matching "value".

If not you'll have to join the two tables together manually (which looks a bit more horrid in lambda syntax):

var foo = db.ParentDataItems.Join(db.ChildDataItems.Where(c => c.Name == "value"),
                                  p => p.ChildDataItemId,
                                  c => c.ParentDataItemId,
                                  (parent, child) => parent);
like image 56
Dave D Avatar answered Nov 28 '25 08:11

Dave D


Using LINQ syntax:

var foo = from p in ctx.Parent
          join c in ctx.Children on c.ParentDataItemID equals p.ParentDataItemID
          where c.Name = "Foo"
          select p;

I recommend LINQPad for authoring and learning about LINQ queries.

like image 34
Dave Swersky Avatar answered Nov 28 '25 06:11

Dave Swersky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!