简体   繁体   English

在外表上需要LINQ to SQL WHERE-clause的帮助

[英]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. 现在我想选择任何具有指定名称和值的ChildDataItem的ParentDataItem。

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. 我更喜欢lambda语法,但要么做。

Using LINQ syntax: 使用LINQ语法:

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. 我推荐LINQPad用于创作和学习LINQ查询。

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". 这将获得任何具有名称与“value”匹配的子项的父数据项。

If not you'll have to join the two tables together manually (which looks a bit more horrid in lambda syntax): 如果不是,你必须手动将两个表连接在一起(在lambda语法中看起来有点可怕):

var foo = db.ParentDataItems.Join(db.ChildDataItems.Where(c => c.Name == "value"),
                                  p => p.ChildDataItemId,
                                  c => c.ParentDataItemId,
                                  (parent, child) => parent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM