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



我有2个查询工作,我希望将它们结合起来以减少数据库调用。

                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;

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

这似乎有点复杂,因为Locations似乎是Articles的多值属性,而您只想加载正确的属性。根据这个类似问题的答案,你需要使用一个select来一次分别返回它们,例如

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语法,所以如果我在那里做了一些愚蠢的事情,我很抱歉。)

您能不能在这里使用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 };

(未测试)

最新更新