linq或lambda表达式中的动态查询C#

时间:2018-03-26 08:37:03

标签: c# entity-framework linq lambda

我需要根据用户输入构建动态查询。

我曾经使用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;
        }
    }
}

现在我使用Entity Framework。我想使用类和linq或lambda表达式

谢谢

1 个答案:

答案 0 :(得分:1)

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

$xs = [
  50,
  100,
  150
];

// Here is example of comparator, it have to take 2 elements, and return boolean signaling weather relationship you want to test holds true
$comparator = function($current, $next) {
  return $current < $next;
};

function isSorted($xs, $comparator){

  $answer = true;
  foreach ($xs as $key => $current) {
    if(!isset($xs[$key + 1]))
        continue;

    $next = $xs[$key + 1];

    $answer = $answer && $comparator($current, $next);
  }

  return $answer;
}

虽然有一句警告,但将日期视为字符串是灾难的收据。日期可以强类型为//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.