【问题标题】:When I group by linq query does not working当我按 linq 分组时查询不起作用
【发布时间】:2019-10-30 09:29:15
【问题描述】:
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.

【问题讨论】:

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


    【解决方案1】:

    您应该去掉 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多