简体   繁体   中英

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.

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.

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

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