在MVC 4中使用Dapper的存储过程

Nav*_*avy 1 c# asp.net asp.net-mvc dapper

我试图使用Dapper和存储过程在MVC中进行CRUD操作,但由于我无法解决的转换错误,我无法将结果从模型返回到控制器.任何人都可以帮助我回复我的结果

这是我的控制器

 public ActionResult AllMobileList()
 {
     MobileMain MM = new MobileMain();
     return View(MM.AllMobileListing().ToList());
 }

 [HttpGet]
 public ActionResult Edit(string MobileID)   
 {
     MobileMain MM = new MobileMain();
     return View(MM.GetMobileList(MobileID));
 }
Run Code Online (Sandbox Code Playgroud)

模型

public IEnumerable<TBMobileDetails> AllMobileListing()
{
    var para = new DynamicParameters();
    para.Add("@Type", 1);
    var result= con.Execute("Sp_MVCDapper", para, commandType: CommandType.StoredProcedure).ToString();

    return result;  // Error happens here
}

public TBMobileDetails GetMobileList(string MobileId)
{
    var para = new DynamicParameters();
    para.Add("@Type", 2);
    para.Add("@MobileId",Convert.ToInt32(MobileId));
    var result = con.Execute("Sp_MVCDapper", para, commandType: CommandType.StoredProcedure).ToString();

    return result;  // Error happens here
}
Run Code Online (Sandbox Code Playgroud)

错误:

无法将类型'string'隐式转换为'System.Collections.Generic.IEnumerable'

我知道这是一个非常常见的错误,我正在做一些愚蠢的错误.

Dir*_*irk 6

您应该使用Dapper的Query<T>扩展方法来获取存储过程调用的结果 - 如果SP使用select语句来返回数据.

Query<T>返回一个IEnumerable<T>,所以你可以简单地使用IEnumerable<TBMobileDetails> AllMobileListing():

return con.Query<TBMobileDetails>(
    "Sp_MVCDapper", para, commandType: CommandType.StoredProcedure)
Run Code Online (Sandbox Code Playgroud)

并为 TBMobileDetails GetMobileList(string MobileId)

var list = con.Query<TBMobileDetails >(
    "Sp_MVCDapper", para, commandType: CommandType.StoredProcedure);

return list.Single(); // assuming that the SP only returns a single item
Run Code Online (Sandbox Code Playgroud)

并且作为评论:如果您的参数是数字,则不要使用string类型.它只会导致后来的头痛.