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

标签 c# asp.net asp.net-mvc dapper

我正在尝试使用 Dapper 和存储过程在 MVC 中执行 CRUD 操作,但由于我无法解决的转换错误,我无法将结果从模型返回到 Controller 。请任何人帮助我应该返回什么作为我的结果

这是我的 Controller

 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));
 }

模型

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
}

错误:

Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable'

我知道这是一个很常见的错误,但我犯了一些愚蠢的错误。

最佳答案

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

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

return con.Query<TBMobileDetails>(
    "Sp_MVCDapper", para, commandType: CommandType.StoredProcedure)

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

请注意:如果您的参数是数字,则不要使用 string类型。它只会在以后引起头痛。

关于c# - 在 MVC 4 中使用 Dapper 的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917093/

相关文章:

c# 将IE浏览器的内容保存为html

c# - LINQ 使用 Automapper 作为第三级属性

c# - 如何从 HttpresponseMessage Asp.net Web Api 返回不记名 token

c# - 图像路径在 CDN 中有效,但在 .css 中无效

c# - 升级到 DotNet Core 2.2 后,Azure 应用服务无法运行

c# - 适用于 Windows Mobile 的 gzip 工具比 SharpZipLib 更好?

c# - Javascript 确认或其他类型的确认

c# - ASP.NET C# 使用列表导航如何在事件导航页面上设置 id ="current"?

asp.net - 尝试通过 Web API 请求检索 Azure blob 时出现 403 错误

c# - 在没有启动的情况下在旧的 ASP.NET MVC 应用程序中创建 HttpClient