结合LINQ查询以减少数据库调用

时间:2013-05-25 12:21:05

标签: linq entity-framework

我有两个有效的查询,我希望将它们组合起来以减少数据库调用。

                var locations = from l in db.Locations
                                where l.LocationID.Equals(TagID)
                                select l;

我这样做是因为我需要l.Name,但有没有办法将上述结果放入下面的查询中?

                articles = from a in db.Articles
                               where
                               (
                               from l in a.Locations
                               where l.LocationID.Equals(TagID)
                               select l
                               ).Any()
                               select a;

我真的会在这里减少任何数据库调用吗?

2 个答案:

答案 0 :(得分:0)

这似乎有点复杂,因为Locations似乎是Articles的多值属性,并且您只想加载正确的属性。根据{{​​3}}对类似的问题,你需要使用一个选择单独返回它们,例如。

var articles = from a in db.Articles
               select new {
                   Article = a,
                   Location = a.Locations.Where(l => l.LocationId == TagId)
               };

首次使用join尝试失败:

var articlesAndLocations = from a in db.Articles
                           join l in a.Locations
                             on l.LocationID equals TagID
                           select new { Article = a, Location = l };

(我通常使用其他LINQ语法,但如果我在那里做了一些愚蠢的话,我会道歉。)

答案 1 :(得分:0)

你能否在这里使用Include()方法拉入与每篇文章相关的位置,然后同时选择文章和位置对象?或者你需要的属性。

include方法将确保您不需要两次访问数据库,但允许您访问相关实体的属性。

你需要在IEnumerable上使用contains方法我相信,这样的话:

var tagIdList = new List() { TagID };

var articles = from a in db.Articles.Include("Locations")
           where tagIdList.Contains(from l in a.Locations select l.LocationID)
           select new { a, a.Locations.Name };

(未测试的)

相关问题