【问题标题】:How can I change this query after migrating to ASP.Net Core 3迁移到 ASP.Net Core 3 后如何更改此查询
【发布时间】:2020-03-28 06:28:50
【问题描述】:

无法翻译...请参阅 go.microsoft.com/fwlink/?linkid=2101038

我不能再使用Include() 了吗?我开始使用原始 SQL 命令会更好吗?

public async Task<IActionResult> Index(int? id)
{
  if (id == null)
  {
    id = 1;
  }

  var pianoContext = _context.Product
    .Include(p => p.IdProductCategoryNavigation)
    .Include(p => p.IdProductTamNavigation)
    .Include(p => p.IdProductTypeNavigation)
    .Where(m => m.IdProductCategory == id || m.IdProductCategoryNavigation.IdPa.Value == 1)
    .Where(m => m.IsAt.Equals(true))
    .GroupBy(m => m.Name)
    .Select(m => m.First());

  if (pianoContext == null)
  {
    return NotFound();
  }
  return View(await pianoContext.ToListAsync());
}

【问题讨论】:

    标签: entity-framework asp.net-mvc-3 asp.net-core linq-to-sql


    【解决方案1】:

    我不能再使用 Include() 了吗?我开始使用原始 SQL 命令会更好吗?

    这与Include() 无关,而是因为您使用的是GroupBy(m=&gt; m.Name)。见breaking chagnes

    这是引用自official docs 的关于Groupby 的描述:

    SQL GROUP BY 也有限制。它要求您仅按标量值进行分组。投影只能包含分组键列或应用于列的任何聚合。 EF Core 识别此模式并将其转换为服务器

    要解决这个问题,您应该使用可以翻译成 SQL 的GroupBy()

    // a lazy query that will be used to query the ids of Product
    var theProductIds = 
        _context.Product
        .Where(m => m.IdProductCategory == id || m.IdProductCategoryNavigation.IdPa.Value == 1)
        .Where(m => m.IsAt.Equals(true))
        .GroupBy(m => m.Name)
        .Select(m => m.Min(p=>p.Id));
    
    // a query that includes all the related navigation properties
    var products = await _context.Product
        .Where(p => theProductIds.Contains(p.Id)) 
        .Include(p => p.IdProductCategoryNavigation)
        .Include(p => p.IdProductTamNavigation)
        .Include(p => p.IdProductTypeNavigation)
        .ToListAsync();
    
    if(products.Count==0){ return NotFound(); }
    return View(products);
    

    上面的查询将被翻译成如下的 SQL 语句:

    SELECT [p].[Id], [p].[CategoryId], [p].[Name], ...
    FROM [Product] AS [p]
    INNER JOIN [ProductCategory] AS [p0] ON [p].[CategoryId] = [p0].[Id]
    INNER JOIN ...
    WHERE [p].[Id] IN (
        SELECT MIN([p1].[Id])
        FROM [Product] AS [p1]
        INNER JOIN [ProductCategory] AS [p2] ON [p1].[CategoryId] = [p2].[Id]
        WHERE ...
        GROUP BY [p1].[Name]
    )
    

    【讨论】:

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