【问题标题】:Dynamic query in linq or lambda expression C#linq 或 lambda 表达式 C# 中的动态查询
【发布时间】:2018-03-26 08:37:03
【问题描述】:

我需要根据用户输入构造一个动态查询。

我曾经使用带有字符串连接的SqlCommand 来做到这一点。

例子:

public ActionResult Receipt_Details(string FromDate, string ToDate, int Branch, int User, int RecietType, int PayMethod)
{
    if (FromDate == "")
        FromDate = "1980-01-01";

    if (ToDate == "")
        ToDate = "2180-01-01";

    string where = " where DmentDate>='"+FromDate+ "' and DmentDate<='"+ToDate +"'";

    if (Branch != 0)   // Branch = 0 means select all branches
        where += " and BranchID = " + Branch;

    if (User != 0)     // User = 0 means select all users
        where += " and UserID = " + User

    if (PayMethod != 0)
        where += " and PayMethodID = " + PayMethod

    string constr = "data source=.;initial catalog=db;integrated security=True;";

    using (SqlConnection con = new SqlConnection (constr))
    {
        con.Open();

        using (SqlCommand com=new SqlCommand())
        {
            com.Connection = con;
            com.command="Select * from Table "+ where;
        }
    }
}

现在我使用实体框架。我想使用类和 linq 或 lambda 表达式

谢谢

【问题讨论】:

  • 我猜这很好。你有什么问题?
  • 问题是如何使用 linq 或 Lambada 表达式做同样的事情,因为现在我使用实体框架
  • 您是否创建了 EF 上下文?你从你身边尝试过的东西..发布你的代码。如果其中有任何错误,我们会为您提供帮助。

标签: c# entity-framework linq lambda


【解决方案1】:

如果您想将此方法重构为使用 EF 和 LINQ 的解决方案,那么它的工作方式基本相同。

//query will be of type IQueryable<T>
var query = context.Receipts;

//modify the query based on your needs
if(Branch != 0)
   query = query.Where(x => x.Branch == Branch);
if (User!=0)
   query = query.Where(x => x.UserId == User);

/* ... and so on */

//execute
return query.ToList() // materialize your query with ToList or FirstOrDefault() or whatever you need.

提醒一句,将日期视为字符串是灾难的收据。日期可以强输入为DateTime

【讨论】:

  • 没错,我必须这样做,因为来自用户的输入返回空字符串
  • 好吧,但你可以应付。我建议改用nullable DateTime。因此,您可以设置默认值或将其保留为空。比使用字符串要好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多