[英]Include dynamic Entity Framework Core
我在我的數據庫中有以下關系,一個product
有幾個presentaciones_prouduct
,並且在我的查詢中,只有當它至少有一個產品演示時,我才需要包含它們,為此目的,並在product
表中創建了一個布爾屬性lista_precios
,如一個指標,這將在內部處理。
進行以下查詢以包含列表,但需要很長時間,而且我有幾個不需要它的產品:
var producto = await _context.Producto
.Select(x => new
{
x.Id,
x.Nombre,
x.NombreSecundario,
x.MarcaId,
x.IdCategoria,
x.IdUnidad,
x.Precio,
x.PrecioCompra,
x.Codigo,
x.CantidadInicial,
x.CantidadMinima,
x.ListaPrecios,
Include------------> x.PresentacionesProducto,
x.Descripcion
})
.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id== IdProducto);
現在我嘗試在系統中造成最少的開銷,只包括列表,如果任何產品有它,這是動態的
if (producto.ListaPrecios) {}
問題:在這種情況下如何進行最有效的咨詢,僅在您有產品介紹的情況下才包括產品介紹
怎么樣: x.PresentacionesProducto.Where(p=>producto.ListaPrecios)
使用您的代碼:
var producto = await _context.Producto
.Select(x => new
{
x.Id,
x.Nombre,
x.NombreSecundario,
x.MarcaId,
x.IdCategoria,
x.IdUnidad,
x.Precio,
x.PrecioCompra,
x.Codigo,
x.CantidadInicial,
x.CantidadMinima,
x.ListaPrecios,
PresentacionesProducto = x.PresentacionesProducto.Where(p=>producto.ListaPrecios),
x.Descripcion
})
.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id== IdProducto);
首先,您必須從 db(如果存在)中獲取該元素,並在必要時加載導航屬性。
代碼:
var producto = await _context.Producto
.AsNoTracking() //Maybe it is not need
.FirstOrDefaultAsync(x => x.Id == IdProducto);
if(producto != null && producto.ListaPrecios)
_context.Entry<Producto>(producto)
.Navigation(nameof(producto.PresentacionesProducto))
.Load();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.