尝试在数据库中查询特定记录时,模型中的此记录具有与其关联的ICollection。下面是一个例子:
假设a有一堆商店:
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...
....not确定下一步该怎么做,或者我可能一开始就走错了方向。
发布于 2019-04-24 01:40:35
您可以通过StoreLocation
完成此操作,但效率会很低,因为您必须查询出所有SaleItem
,然后在内存中对它们进行过滤:
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();
https://stackoverflow.com/questions/55816533
复制相似问题