包含动态实体框架核心

时间:2020-02-08 15:32:08

标签: c# .net linq entity-framework-core

enter image description here

我在数据库中具有以下关系,一个product有多个presentaciones_prouduct,在我的查询中,仅当它具有至少一个产品表示形式时,才需要包括它们,并且在lista_precios表中创建了一个布尔属性product,作为指示符,它将在内部处理。

进行以下查询以包括该列表,但是需要很长时间,并且我有一些不需要它的产品:

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) {}

问题:在这种情况下,最有效的咨询会是如何进行,仅当您有产品展示时才包括它们

2 个答案:

答案 0 :(得分:1)

那怎么办:x.PresentacionesProducto.Where(p => producto.ListaPrecios)

使用您的代码:

globalOne.json

答案 1 :(得分:0)

首先,必须从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();