坚持使用linq查询

时间:2012-07-30 05:36:57

标签: c# linq entity-framework-4

我坚持使用这个linq查询,所有我需要的是优化最后的价格计算,因为我得到大约1000篇文章,&很多销售,所以它变得缓慢......

var result = from article in db.Entities.Articles 
select new{
     article.ID_ART,
     article.Designation,
     article.BuyPrice,
     article.SellPrice,
     LastPrice = (from sale in article.Sales where sale.Date == article.Sales.Max(X => X.Date) select sale.Price).FirstOrDefault()==0?
     article.BuyPrice: (from sale in article.Sales where sale.Date == article.Sales.Max(X => X.Date) select sale.Price).FirstOrDefault()
     }

2 个答案:

答案 0 :(得分:3)

var result = from article in db.Entities.Articles 
    let lastPrice = (from sale in article.Sales 
                     orderby sale.Date descending 
                     select sale.Price).FirstOrDefault()
    select new
    {
        article.ID_ART,
        article.Designation,
        article.BuyPrice,
        article.SellPrice,
        LastPrice = lastPrice ==0 ? article.BuyPrice : lastPrice
    }

答案 1 :(得分:1)

您应该joinInclude销售。我假设因为它是文章的导航属性,它是一个FK表。

只需使用from article in db.Entities.Articles.Include("Sales")代替。

这将加载销售以供参考,并防止它在初始化匿名类型时运行子查询。