微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Linq EF在.Select内部或之后添加条件

如何解决如何使用Linq EF在.Select内部或之后添加条件

我的问题很简单,但是我无法解决,我已经在互联网上进行搜索,但是其中一个与我的问题相符。 这是我的代码

chrome.debugger.attach(debuggeeId,'1.3',async () => {
  const send = (cmd,params = null) =>
    new Promise(resolve =>
      chrome.debugger.sendCommand(debuggeeId,cmd,params,resolve));
  await send('Page.enable');
  const {frameTree} = await send('Page.getResourceTree');
  const frameQueue = [frameTree];
  const results = [];
  for (const {frame,childFrames,resources} of frameQueue) {
    frameQueue.push(...childFrames);
    const frameId = frame.id;
    for (const {url,type} of resources) {
      if (type === 'Stylesheet') {
        results.push({
          url,frameUrl: frame.url,...await send('Page.getResourceContent',{frameId,url}),});
      }
    }
  }
  console.log(results);
});

我正在尝试在 public Producto VerificarExTalla(int id,bool related = true) { var productos = _context.Productos.AsQueryable(); if (related) { productos = productos .Include(s => s.Categoria) .Include(s => s.DetalleTallas) .Include(s => s.DetalleTallas.Select(a => a.Talla)); } return productos .Where(s => s.Id == id) .SingleOrDefault(); } 后执行条件。这是我尝试过但没有起作用的方法

.Select() 

并在.select内也尝试了此操作

.Include(s => s.DetalleTallas.Select(a => a.Talla).Where(a => a.EstadoTallaa == false));

两者都给了我同样的错误

包含路径表达式必须引用在类型上定义的导航属性。使用虚线路径作为参考导航属性,使用“选择”运算符作为集合导航属性。 参数名称:路径'

解决方法

看看您的代码,您似乎想要实现以下目标-

  1. 获取Productos,包括相关的Categoria和DetalleTallas
  2. DetalleTallas列表将被过滤,以包括EstadoTallaa == false的记录
  3. 仅获取ID与参数值匹配的Productos

作为一个简单的逻辑程序员,我想写如下-

productos = productos.Where(p=> p.Id == id)
                     .Include(s => s.Categoria)
                     .Include(s => s.DetalleTallas.Where(d=> d.EstadoTallaa == false));

但是可惜它无法正常工作!它将显示错误“在Include中使用的Lambda表达式无效”。

所以可以这样重写-

productos = productos.Where(p=> p.Id == id)
                     .Select(p => new Productos
                     {
                        Id = p.Id,Categoria = p.Categoria
                        // some other properties of Productos
                        DetalleTallas = p.DetalleTallas.Where(d => d.EstadoTallaa == false).ToList()
                      });
,

内联显示的错误表明EF的导航功能引发了异常。更准确地说,.Include()不能按预期工作

包含路径表达式必须引用导航属性 在类型上定义。使用虚线路径进行参考导航 属性和用于集合导航的Select运算符 属性。参数名称:路径'

.AsQueryable() DbSet上调用了Productos的原因,它不再使它成为对实体查询的限制,而变成了普通列表查询。为了使.Include()正常工作,请确保直接在DbSet本身上调用.Include()

public Producto VerificarExTalla(int id,bool related = true)
{
    if (related)
    {
        productos = _context.Productos
            .Include(s => s.Categoria)
            .Include(s => s.DetalleTallas)
            .Include(s => s.DetalleTallas.Select(a => a.Talla));
    }

    return _context.Productos
        .Where(s => s.Id == id)
        .SingleOrDefault();

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。