views:

49

answers:

2

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.

+2  A: 

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.

Dave Swersky
Thanks for the link to LINQPad - I actually have it installed on one of my machines - I guess I could start using it.
jhorback
+1  A: 

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);
Dave