我正在尝试使用 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/