【问题标题】:EF Core and ASP.net MVC Query too largeEF Core 和 ASP.net MVC 查询太大
【发布时间】:2020-08-14 01:56:21
【问题描述】:

我正在尝试确定更改数据模型或 linq 查询以减少查询的冗余 SQL 列的最佳方法。

我有一个客户模型、商品模型和 customerItem 连接实体。

我需要分别来自客户模型和项目模型的客户名称和项目名称。

如果我使用 SQL 分析器查看 SQL,则从所有 3 个表中选择 *。

如何从 customerITEm 中选择 * 仅包括 customer.customerName,Item.ItemName ?

var aMRSContext = _context.CustomerItems.Include(c => c.Customer).Include(c => c.Item);

【问题讨论】:

  • 从 customerITem 中选择 customer.customerName,Item.ItemName
  • 使用.Select() 从对象图中仅投影您需要的列。在这种情况下,您不需要使用 .Include(),因为 EF 将编写一个查询来仅检索您需要的列。

标签: entity-framework asp.net-core model-view-controller


【解决方案1】:

您可以使用 ViewModel 来显示数据:

public class CustomerItemVM
{
    public string CustomerName { get; set; }
    public string ItemName { get; set; }
}

控制器

var aMRSContext = _db.CustomerItems
            .Select(c=>new CustomerItemVM { 
                CustomerName=c.Customer.CustomerName,
                ItemName=c.Item.ItemName
            })
            .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2021-07-22
    相关资源
    最近更新 更多