【问题标题】:ASP.NET Core 2.2 - Simple DB Query QuestionASP.NET Core 2.2 - 简单的数据库查询问题
【发布时间】:2019-04-23 17:29:08
【问题描述】:

尝试在数据库中查询特定记录,模型中的该记录具有与之关联的 ICollection。所以这里有一个例子:

假设有很多商店:

class StoreLocation {
    public int StoreId
    public string LocationName
    public ICollection<SaleItems> SaleItems
}

class SaleItems {
    public int SaleItemId
    public string ItemName
    public string ItemCost
}

所以使用实体框架...

如何在被搜索的特定商店中搜索价格低于 5 美元的 SaleItems?

var SaleItemsAtStore = _context.StoreLocations
.Where(location => location.StoreId == SomethingUserInputs

var CheapSaleItems = SaleItems...

....不知道该怎么做,或者我一开始就走错了方向。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.2


    【解决方案1】:

    你可以通过StoreLocation来做,但是效率很低,因为你必须查询出所有SaleItems然后在内存中过滤它们:

    var store = await _context.StoreLocations.Include(x => x.SaleItems)
        .SingleOrDefaultAsync(x => x.StoreId == storeId);
    var saleItems = store.SaleItems.Where(x => x.ItemCost < 5);
    

    另外,更好的是,您可以仅显式加载您想要的销售项目,但您仍然必须先查询商店,这意味着一个不必要的查询:

    var store = await_context.StoreLocations.FindAsync(storeId);
    var saleItems = await _context.Entry(store)
        .Collection(x => x.SaleItems).Query()
        .Where(x => x.ItemCost < 5).ToListAsync();
    

    最好的方法是在您的 SaleItem 实体上拥有一个显式外键属性:

    [ForeignKey(nameof(StoreLocation))]
    public int StoreLocationId { get; set; }
    public StoreLocation StoreLocation { get; set; }
    

    然后,您可以简单地这样做:

    var saleItems = await _context.SaleItems
        .Where(x => x.ItemCost < 5 && x.StoreLocationId == storeId).ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 2019-10-30
      • 2020-04-22
      • 2019-06-19
      • 2019-07-17
      相关资源
      最近更新 更多