简体   繁体   English

实体框架中的Customized(Where)子句

[英]Customized ( Where) clause in Entity Framework

I am trying to put a Where Clause in reading a SQL server database table where some conditions are depending on other variables, I have 7 fields to do the filtering in the database and are entered by the user , anyone can have a value or can be null . 我试图在阅读某些条件取决于其他变量的SQL Server数据库表中放置Where子句,我有7个字段在数据库中进行过滤,并由用户输入,任何人都可以有一个值或可以空值 。 it should look like this if all search variables Var1, etc are not null 如果所有搜索变量Var1等都不为空,则应如下所示

Select * from Table1 where Field1 = var1 and Field2 = Var2 and Field3 = Var3

However if Var2 for example is null it should be ignored in the Select statement and it will look like 但是,如果Var2例如为null,则应在Select语句中将其忽略,并且它将看起来像

Select * from Table1 where Field1 = var1 and Field3 = Var3

It's much like SQL string, however when using the select statement with Lambda expression as in Entity Framework, I could not find any thing like simple sql string . 这很像SQL字符串,但是当在Entity Framework中使用带Lambda表达式的select语句时,我找不到像简单sql string这样的东西。

I am using VS2017 with c# coding language for an ASP.NET Core application. 我正在将VS2017与c#编码语言一起用于ASP.NET Core应用程序。 Database server is SQL2016 . 数据库服务器是SQL2016。

This looks pretty much standard, however, I could not find a solution. 这看起来很标准,但是我找不到解决方案。 Does anyone have a good solution? 有没有人有一个好的解决方案?

If I understand correctly what you want, the standard way is this: 如果我正确理解您想要什么,则标准方法是这样的:

using (var context = new SomeContext())
{
    IQueryable<SomeEntity> query = context.SomeEntities;

    if (var1 != null)
        query = query.Where(x => x.Field1 == var1);

    if (var2 != null)
        query = query.Where(x => x.Field2 == var2);

    // and so on

    // use the query somehow
}

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

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