实体框架条件查询构建

本文关键字:构建 查询 条件 框架 实体 | 更新日期: 2023-09-27 18:21:07

我在使用实体框架创建复杂查询时遇到问题。我想根据构造此类查询时给出的参数,将额外的数据提取到我的linq实体中。以下是其中的示例:

        if (featureEnabled)
        {
            query = query.Where(n => *condition*);
        }

我创建了这样的复杂对象:

n => new Entity{
    Property = n.Something
    '* ... *'
    PropertyN = n.SomethingN,
}

如果启用了该功能,我想将额外的数据加载到实体中(就像在示例中一样):

public DoSomething(bool featureEnabled, feature2Enabled, etc.)
{
  return n => new Entity{
    Property = n.Something,
    '* ... *'
    PropertyN = n.SomethingN,
    Feature = (featureEnabled) ? *fetch some data from navigation property* : 0,
    Feature2 = (feature2Enabled) etc.
  }
}

在上面的示例中,参数(featureNEnabled)将被转换为sql参数。如何在查询构建时进行这样的操作?

实体框架条件查询构建

您的意思是在initializer中要使用if条件吗?

如果是这样,我就不可能了。要使用if条件,必须将其放在初始值设定项之外

var a = new MyClass{
prop1 = n.prop1,
prop2 = n.prop2,
prop3 = n.prop3,
};
a.propN = boolCondition ? n.PropN : 0;

我终于在这个博客上找到了问题的答案使用此代码,您可以调用表达式。Merge(expression2)和两个对象的初始化列表将合并到一个查询中。