当我按linq分组查询时不起作用

时间:2019-10-30 09:29:15

标签: c# .net-core .net-core-3.0 entity-framework-core-3.0

using (var tigerContext = new TigerContext())
        {
            var stockRemaningList = from stocks in tigerContext.Stock
                join item in tigerContext.ItemsSum
                    on stocks.LOGICALREF equals item.STOCKREF  into temp 
                from x in temp.DefaultIfEmpty()

                group x by new { stocks}
                into s
                select new StocksRemaning
                {
                    StockCode = s.Key.stocks.CODE,
                    StockRef = s.Key.stocks.LOGICALREF,
                    StockName = s.Key.stocks.NAME,
                    ActualStock = s.Sum(i=>i.ONHAND)

                };
            return stockRemaningList.ToList();


        }

这是我的错误。我该如何解决这个错误

The LINQ expression 'GroupBy<TransparentIdentifier<Stock, ItemsSum>, <>f__AnonymousType10<Stock>, ItemsSum>(
    source: LeftJoin<Stock, ItemsSum, int, TransparentIdentifier<Stock, ItemsSum>>(
        outer: DbSet<Stock>, 
        inner: DbSet<ItemsSum>, 
        outerKeySelector: (s) => s.LOGICALREF, 
        innerKeySelector: (ı) => ı.STOCKREF, 
        resultSelector: (s, ı) => new TransparentIdentifier<Stock, ItemsSum>(
            Outer = s, 
            Inner = ı
        )), 
    keySelector: (ti) => new { stocks = ti.Outer }, 
    elementSelector: (ti) => ti.Inner)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

1 个答案:

答案 0 :(得分:0)

您应该在group by子句中摆脱匿名类型,这样EF引擎将其转换为实际SQL不会有问题。

作为建议,我建议您习惯使用更有意义的名称,例如from leftJoined in tempJoin.DefaultIfEmpty()。这样,将来其他编码人员或您自己都无需问“ X和S到底是什么?”

using (var tigerContext = new TigerContext())
{
    var stockRemaningList = 
        from stocks in tigerContext.Stock
        join item in tigerContext.ItemsSum on stocks.LOGICALREF equals item.STOCKREF  into tempJoin 
        from leftJoined in tempJoin.DefaultIfEmpty()
        group leftJoined by stocks into grouped
        select new StocksRemaning
        {
            StockCode = grouped.Key.CODE,
            StockRef = grouped.Key.LOGICALREF,
            StockName = grouped.Key.NAME,
            ActualStock = grouped.Sum(i=>i.ONHAND)
        };
    return stockRemaningList.ToList();
}