简体   繁体   English

动态引用 IQueryable 中的实体框架列<t></t>

[英]Dynamically refer to Entity Framework columns in IQueryable<T>

I know that some similar question were wandering around stack overflow however though none of them seem to work the way I want to.我知道一些类似的问题在堆栈溢出中徘徊,但是尽管它们似乎都没有按照我想要的方式工作。 Here's the idea what I want to achieve:这是我想要实现的想法:

// arrays vary depends what's in bigger loop
string[] columnNames = {"id", "name", "surname", "address", "phone"} 

// ...

foreach (string columnName in columnNames)
{
    if (condition)
    {
        IQueryable<tableType> query = from x in dbContext where x.(**columnName**).contains(otherVariable) select x;
    }
    // ...
    // Another queries wrapped in if conditions
}

I've tried this with typeof() and Type.GetProperty() which I found here and it seems not be working whatsoever.我已经用我在这里找到的 typeof() 和 Type.GetProperty() 进行了尝试,它似乎没有任何工作。 Another thing is I want this to be as much as possible in standards with current best practices and if I'm looking into wrong direction then where should I point to?另一件事是我希望这尽可能符合当前最佳实践的标准,如果我正在寻找错误的方向,那么我应该指向哪里? I need to get this sort of method reusable for tens of hundreds of views and tables.我需要让这种方法可重用于数以百计的视图和表。

cheers,干杯,

Instead of storing strings in your array, you should store expressions.您应该存储表达式,而不是在数组中存储字符串。

Expression<Func<TableType, bool>>[] conditions = new {
    x => x.ID > 5,
    x => x.Name > "M" };

etc. Than you can query等比你可以查询

var query = dbContext.YourTable.Where(conditions[1])

That's a little simpler and easy to read, than using reflection or dynamics or whatever.这比使用反射或动态或其他任何东西更简单易读。

You can combine multiple conditions also, by multiple where clauses.您也可以通过多个 where 子句组合多个条件。

Since your sample implied a where clause, I had to invent some boolean expressions here.由于您的示例暗示了 where 子句,因此我不得不在这里发明一些 boolean 表达式。

Just don't start with storing strings (unless these strings are entered by the user)只是不要从存储字符串开始(除非这些字符串是由用户输入的)

I have to answer my question with link to another post answered by @Aleks Andreev我必须通过@Aleks Andreev回答的另一篇文章的链接来回答我的问题

LINQ where condition with dynamic column LINQ where 条件与动态列

This is exactly what I was looking for.这正是我一直在寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM