【问题标题】:Is there a way to modify data being returned in IQueryable for an OData request?有没有办法修改在 IQueryable 中为 OData 请求返回的数据?
【发布时间】:2014-07-09 13:31:51
【问题描述】:

我有一个 Web Api 2 服务器、一个实体框架数据层和一个 BreezeJS 客户端。我有一些额外的属性没有映射到我想在查询时设置的数据库。比如:

public class Foo
{
    // Various mapped properties
    // ...

    // These properties are not mapped, and I want
    // to set them on the returned data depending
    // on the current user's roles/authorization
    public bool CanEdit { get; set; }
    public bool CanDelete { get; set; }
}

[BreezeController]
public class BreezeController : BaseController
{
    // ...

    [HttpGet]
    public IQueryable<Foos> Users()
    {
        // How can I set the CanEdit and CanDelete properties
        // here (and only on the data as filtered by the OData
        // queries)?
        return Db.Foos; // Db.Foos is a DbSet<Foo>
    }
}

有什么办法吗?

注意:确定CanEdit/CanDelete 的逻辑过于复杂,无法包含在 LINQ to Entities 查询中。

【问题讨论】:

  • 有什么理由必须是 IQueryable 吗?为什么不能返回 IEnumerable?如果你真的想要返回一个 IQueryable,你可以运行查询,然后在返回的数据上设置这些属性,并返回 .AsQueryable()
  • 这些属性的值是如何确定的?
  • 对不起@malik,我刚刚意识到这个问题听起来很笼统。我修复了标题以反映我希望这需要在 Web API 中处理 OData 查询
  • @jmcilhinney,可以说逻辑可能很复杂并且无法通过 LINQ to Entities 转换为 SQL 查询吗?
  • @Eric 您不能将非映射(复杂)属性传递给 Linq to Entities。你可以这样做:if (CanEdit) { Db.Foos.Where(w =&gt; w.Whatever); }

标签: c# entity-framework asp.net-web-api odata breeze


【解决方案1】:

我最终通过从QueryHelper 派生并连接到PostExecuteQuery() 来解决这个问题。看我的回答here

【讨论】:

    【解决方案2】:

    就 OData 而言,有 2 个概念适用于您的案例。

    第一个是开放类型,它允许您向实体添加未定义的属性。您可以参考此博客How to Use Open Type in OData 了解更多信息。并且最新的 WebApi OData 已经支持开放的复杂类型。

    第二个是自定义注解,可用于定义与您的实体相关的附加信息。在您的情况下,您可以将“@Foo.CanEdit:true”写入实体有效负载,以告诉客户端您的 Foo 实体是可编辑的。 “CanDelete”也一样。

    如果您想了解更多信息,我可以提供有关开放类型和自定义注释的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2013-04-25
      • 2015-04-09
      • 2018-02-02
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      相关资源
      最近更新 更多