1

我被这个 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()
     }
4

2 回答 2

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
    }
于 2012-07-30T05:43:28.803 回答
1

你应该要么joinInclude销售。我假设因为它是文章上的导航属性,所以它是一个 FK 表。

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

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

于 2012-07-30T05:40:41.773 回答