创建不具有实体类型属性的动态 LINQ 语句
我正在尝试创建一个 Linq 语句,该语句查询实体上作为属性存在的列以及实体数据库中不作为属性存在的列。
例如,我有一个 Book 实体的集合。每本书都有一个 ID 和 Title 属性以及数据库中的匹配列。但是,假设 Book 的表还包含 Author 的列字段,而我的 Book 实体没有此字段。
涉及 ID 和标题的普通查询可能如下所示:
Books.Where(b=>b.ID == 123 && b.Title == "Title")
但是,我还想动态地将“ AND Author = 'Name' ”的等效内容添加到上述查询中。 Book 对象上不存在 Author 属性。
额外的字段及其应包含的值实际上在字典中可用。因此,我需要向查询动态添加多个 AND [FieldName] = '[Value]' 条件。
这可能有助于解释为什么我需要它来知道我正在使用 Azure 表存储,并且我已经覆盖了将 Book 实体转换为存储在 Azure 中的 XML 的序列化。
编辑 -
我尝试过使用 Dynamic Linq 库,但它不起作用。
Books.Where(b=>b.ID == 123 && b.Title == "Title").Where("Author = @0", "SomeName").ToList();
投掷: System.Linq.Dynamic.ParseException:类型“Book”中不存在属性或字段“Author”。
另外,
我知道使用 Books.AddQueryOption("$filter","Author eq 'SomeName'") 在单独使用时有效。但我不知道如何将 AddQueryOption 与现有的Where 语句一起使用。
I'm trying to create a Linq statement that queries both columns that exist on my entity as properties and those that don't but exist as columns in the database for the entity.
For example, I have a collection of Book entities. Each Book has an ID and Title property and a matching column in the database. But, lets say the table for Book also contains a column field for Author and my Book entity doesn't have this.
A normal query involving the ID and the Title might look like this:
Books.Where(b=>b.ID == 123 && b.Title == "Title")
But, I want to also dynamically add the equivalent of " AND Author = 'Name' " to the above query as well. The Author property doesn't exist on the Book object.
The extra fields and the values they should contain will actually be available in a Dictionary. So I will need to dynamically add multiple AND [FieldName] = '[Value]' conditions to the query.
It might help explain why I would need this to know that I'm using Azure Table Storage and I have overridden the serialize that turns a Book entity into the XML stored in Azure.
Edit -
I've tried using the Dynamic Linq library but it does not work.
Books.Where(b=>b.ID == 123 && b.Title == "Title").Where("Author = @0", "SomeName").ToList();
Throws:
System.Linq.Dynamic.ParseException: No property or field 'Author' exists in type 'Book'.
Also,
I know using Books.AddQueryOption("$filter","Author eq 'SomeName'") works when used by itself. But I have no idea how to use AddQueryOption along with an existing Where statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果不将 Author 添加到 Book,您要么必须传递另一个带有 Author 的对象:
或者从 Book 继承并为此目的添加一个 Author 属性:
Without adding Author to Book, you would either have to pass another object with Author on it:
Or inherit from Book and add an Author property just for this purpose:
这对于 LINQ 来说是不可能的
This is not possible with LINQ
尝试以下代码:
这是
IQueryable
类型的扩展方法:Try the following code:
This is an extension method for
IQueryable
type: