如何将原始查询从控制器传递到模型

时间:2019-07-12 05:53:12

标签: asp.net-mvc dapper

我想将原始查询从Controller传递到Model。我在模型中编写了ConnectionString,还介绍了如何在模型中编写ExecuteWithReturnExecuteWithOutReturn函数

这是我的示例代码:

控制器:

public ActionResult  RawQuery(int? EmployeeID)
{
     if (EmployeeID == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     else
     {
         string query = "SELECT * FROM Employee WHERE EmployeeID =@EmployeeID";
         DapperORM.ExecutewithReturn(query);
        return RedirectToAction("Index");
     }
}

型号:

    public static class DapperORM
{

     public static void ExecuteWithOutReturn(string sql)
      {
     using (SqlConnection con = new SqlConnection(connectionstring))
     {
        //which code can I write here to execute row query without  return  
     }
 }

 public static void ExecuteWithReturn(string sql)
 {
      using (SqlConnection con = new SqlConnection(connectionstring))
      {
          //which code can I write here to execute row query with  return
      }
 }

}

1 个答案:

答案 0 :(得分:0)

示例代码:

public static void ExecuteWithoutReturn(string sql) {
      using (SqlConnection connection = new SqlConnection(connectionString)) {
          //which code can I write here to execute row query with out return
          connection.Execute(sql, commandType : CommandType.Text); 
      }
 }

//Generic method to fetch List 
public static IEnumerable<T> ExecuteWithReturn<T>(string sql) //pass return type of list
{
      using (SqlConnection connection = new SqlConnection(connectionString)) {
           return connection.Query<T>(sql).ToList();
     }
}