【问题标题】:Dynamic Predicate for Selecting Different Columns of an Entity用于选择实体的不同列的动态谓词
【发布时间】:2013-02-13 14:09:45
【问题描述】:

我需要根据用户选择的页面模式在网格中显示实体的所有或更少属性。例如我有三种页面模式

Minimal (will show 8 properties of an entity in the grid)

Standard (will show 12 properties of an entity in the grid)

Extended (will show 15 properties of an entity in the grid)

如何使 Select 谓词动态化,以根据用户页面模式包含指定的实体列数。假设我有 15 个属性的实体公司,我想做这样的事情

dbContext.Companies.Select([predicate for choosing different no of columns?])

【问题讨论】:

    标签: linq entity-framework entity predicate


    【解决方案1】:

    您无法使用Predicates 解决此问题,因为它们总是返回bool

    你需要的是一个函数表达式,它接受一个Company 对象作为参数并返回一个object。具体来说,你需要一个Expression<Func<Company, object>>

    这是定义三种选择类型的方法:

    Expression<Func<Company, object>> minimal = e => new { e.Prop1, ..., e.Prop8 };
    Expression<Func<Company, object>> standard = e => new { e.Prop1, ..., e.Prop12 };
    Expression<Func<Company, object>> extended = e => new { e.Prop1, ..., e.Prop15 };
    

    然后根据需要使用它们:

    dbContext.Companies.Select(minimal);
    // or
    dbContext.Companies.Select(standard);
    // or
    dbContext.Companies.Select(extended);
    

    【讨论】:

    • 感谢 wolf 提供此解决方案,但我有一个问题。我有一个管理部分,管理员可以在其中选择要在主页上显示的属性/列。所以我得到了一个 8、12 或 15 列的字符串数组,我将如何在上述解决方案中添加这些列。
    • @Waqas 我尝试了多种方式来做到这一点,但到目前为止还没有成功。我认为解决方案是构建一个表达式,用实体的属性填充动态对象,但不知道该怎么做,甚至不知道它是否可能。 This answer 给了我希望,但我还需要进一步挖掘。
    • 谢谢@wolf,我也发现这个链接可能对你也有帮助。 albahari.com/nutshell/predicatebuilder.aspx
    • @Waqas 不错的链接,但我认为这只是关于构建谓词(返回 bool 并可用于 LINQ 过滤器的函数)。我不知道它是否有助于构建select 列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多