LINQ to Entities - 限制包含的表

发布于 2024-09-11 16:02:01 字数 598 浏览 2 评论 0原文

使用具有一对多关系的两个表(例如 Make -> Model),如何在 IQueryable 函数中返回具有有限模型子级的 Make?

当我传入“camry”作为变量时,我想取回一辆只有孩子称为“camry”的丰田汽车,而不是所有孩子。基本上,我想重新创建此 SQL 语句:

SELECT
    MakeName,
    ModelName
FROM
    Make
    LEFT OUTER JOIN Model ON Model.MakeId = Make.MakeId
WHERE
    Model.ModelName = 'camry'

到目前为止,LINQ 语句将如下所示:

return this.ObjectContext.Make
    .Include("Model")
    .Where(make => make.Model.ModelName.Equals("camry")

这显然在语法上不正确,因为Where 子句中的 .Model 是一个实体集合,并且没有 .ModelName 属性。

如何限制包含的表?这在 LINQ to Entities 中可能吗?

Using two tables with a one to many relationship (such as Make -> Model), how do I return a Make with limited Model children in an IQueryable function?

When I pass in “camry” as a variable, I want to get back a Toyota Make with only children called “camry”, not all children. Basically, I want to recreate this SQL statement:

SELECT
    MakeName,
    ModelName
FROM
    Make
    LEFT OUTER JOIN Model ON Model.MakeId = Make.MakeId
WHERE
    Model.ModelName = 'camry'

So far the LINQ statement would look like this:

return this.ObjectContext.Make
    .Include("Model")
    .Where(make => make.Model.ModelName.Equals("camry")

This obviously isn’t syntactically correct, because the .Model in the Where clause is an entity collection and doesn’t have a .ModelName property.

How do you limit the included tables? Is this possible in LINQ to Entities?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心清如水 2024-09-18 16:02:01

请注意,这是我的想法,我没有费心去编译,所以有些东西可能有点不对劲:

return this.ObjectContext.Make.Include("Model")
    .Where(make => make.Models.Any(model => model.ModelName == "camry"))

另请注意,我认为制作将有“模型”而不是“模型”

编辑:

我不明白问题正确。这是您想要的查询:

return this.ObjectContext.Model.Include("Make")
    .Where(model => model.ModelName == "camry")

Note, this is off the top of my head, and I didn't bother to compile so something might be a bit off:

return this.ObjectContext.Make.Include("Model")
    .Where(make => make.Models.Any(model => model.ModelName == "camry"))

Also note that I think the make will have "Models" not "Model"

EDIT:

I didn't understand the question correctly. Here is the query you want:

return this.ObjectContext.Model.Include("Make")
    .Where(model => model.ModelName == "camry")
冷︶言冷语的世界 2024-09-18 16:02:01

这应该也有效:

from make in ctx.Makes
from model in make.Models
where model.Name == "camry"
select new 
{
   Make = make, 
   Model = model
}

This should work as well:

from make in ctx.Makes
from model in make.Models
where model.Name == "camry"
select new 
{
   Make = make, 
   Model = model
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文