【问题标题】:asp.net mvc linq to sql issue with nullable variables带有可为空变量的 asp.net mvc linq to sql 问题
【发布时间】:2013-09-19 12:12:17
【问题描述】:

我有一个 asp.net mvc 项目,其中有搜索过滤器表单和来自我的表单的 8 个参数,并且必须为空。当我填充搜索表单中的所有字段时,一切正常。但是当我持有缺失的字段时,它会返回表中的所有行。我有下一个表达式:

var model = repository.GetRows()
.Where(x => x.Var1 == Var1 || x.Var2 == Var2 || 
x.Var3 == Var3 || x.Var4 == Var4 || 
x.Var5 == Var5 || x.Var6 == Var6 || 
x.Var7 == Var7 || x.Var8 == Var8).ToList();

检查空变量有什么技巧吗?因为我要写很多if/else语句,我觉得是不对的。

【问题讨论】:

  • 你不应该使用&&吗?
  • 因为当我使用 && 时,它返回 null 语句等。无行

标签: c# asp.net asp.net-mvc linq asp.net-mvc-4


【解决方案1】:

您可以使用空合并运算符“??”

where(x => x.Var1 == (Var1 ?? x.Var1));

这只是说如果 Var1 为空,则使用字符串“SomeValue”。

【讨论】:

  • 但是当我的变量为 null 时,我需要它不能包含在我的表达式中。在这种情况下我需要做什么?
  • where(x => x.Var1 == (Var1 ?? x.Var1));这将表示如果 Var1 为 null,则在 x.var1 等于自身时返回,从而使子句自行取消。
  • 哪里 (x => x.Var1 == null || x.Var1 == Var1)
【解决方案2】:

首先我建议你从 repository.GetRows() 返回 IQueryable 然后你可以像这样执行查询:-

public List<Entity.Student> SearchStudent(string Name, int Age, string EmailAddress, string CountryName)
    {
        IQueryable<Entity.Student> lstStudents = this.GetAllStudent();
        if (!string.IsNullOrEmpty(Name))
        {
            lstStudents = lstStudents.Where(node => node.FirstName.Equals(Name) || node.LastName.Equals(Name));
        }
        if (Age > 0)
        {
            lstStudents = lstStudents.Where(node => node.Age == Age);
        }
        if (!string.IsNullOrEmpty(EmailAddress))
        {
            lstStudents = lstStudents.Where(node => node.Email.Equals(EmailAddress));
        }
        if (!string.IsNullOrEmpty(CountryName))
        {
            lstStudents = lstStudents.Where(node => node.Country .Equals(CountryName));
        }
        return lstStudents.ToList<Entity.Student>();
    }

这种方式是 DLinq 专家推荐的。

【讨论】:

  • 当 name != null & age != null 时,它是否只返回 Name 行?
  • 或按姓名添加 lstStudents 按年龄添加 lstStudents?
  • 如果 name 和 age 不为 null 那么它将生成如下 sql 查询:- select * from tblStudent where name = 'name' and age =10 然后它会为你抛出结果
  • 你能想一想,这段代码会生成什么 sql 查询 "where(x => x.Var1 == (Var1 ?? x.Var1));"它正在向您的 sql 查询添加一个条件,而不需要此条件。为什么我们要在 sql 查询中再添加一个条件。它会影响性能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多