尝试获取以下SQL的linq查询(或lambda语法),该SQL选择连接表中具有等于“ blob”的属性的所有“数据”。

例外:没有明确使用Join,但是

select data.*
from data
    join settings on data.DataID = settings.DataID
where settings.Attribute = 'blob'


明确定义联接

from d in dbcontext.Data
  join s in dbcontext.Settings on d.DataID equals s.DataID
where s.Attribute == "blob"
select d


但是有一种使用上下文dbcontext.Data.Settings的方法
喜欢以下内容吗?

from d in dbcontext.Data
where d.Settings.Attribute == "blob"
select d


设置是集合类型,因此,诸如.Contains和.Where之类的内容就浮现在脑海中。

使用。包含,我的理解是我将需要传递一个对象类型

where d.Settings.Contains(new Settings(d.DataID, "blob", null))


但我不在乎null(Value)匹配,只关心列设置

一些表结构

Data
   DataID
   Name

Settings
    DataID
    Attribute
    Value

最佳答案

据我了解,您具有Settings集合导航属性,因此您可以简单地使用它(“ navigate”)来代替显式联接:

from d in dbcontext.Data
from s in d.Settings
where s.Attribute == "blob"
select d


或者,您可以使用Any扩展方法,在这种情况下,该方法比Contains更合适(尽管也可以使用Contains,但需要与Select结合使用):

dbcontext.Data.Where(d => d.Settings.Any(s => s.Attribute == "blob"))


为了完整起见,这是Contains版本:

dbcontext.Data.Where(d => d.Settings.Select(s => s.Attribute).Contains("blob"))

10-07 19:39
查看更多