如何调用使用空格返回列的存储过程 [英] How to call stored procedure that returns columns with spaces
问题描述
我试图使用实体6.0调用存储过程。在寻找这些解决方案后, here 和这里,他们没有解决问题。问题是其中一个返回的列中有空格(我无法更改存储过程)。我没有成功尝试以下操作:
I'm trying to call a stored procedure using entity 6.0. After looking to these solutions here and here, they didn't solve the problem. The issue is that one of the returned columns has a spaces in it (I'm unable to change the stored procedure). I've have tried the following with no success:
MyModel.cs
MyModel.cs
using System;
...
namespace ...
{
public class MyModel
{
[Display(Name = "ID")]
public string id{ get; set; }
[Display(Name = "Number Of ID")]
[Column("Number Of ID")]
public int number_Of_ID { get; set; }
}
public class MyModelContext : DbContext
{
public DbSet<MyModel> MyModels{ get; set; }
}
}
MyController.cs
MyController.cs
using System;
...
namespace ...
{
public class MyController : Controller
{
private MyEntities db = new MyEntities ();
public ActionResult Index()
{
var query = @"exec usp_getIds";
var results = db.Database.SqlQuery<MyModel>(query);
return View(results);
}
}
调试代码时,我的模型有一个值 id
而不是 number_Of_ID
。该值始终为0.我还尝试将数据类型更改为字符串
,并返回 null
。请帮助。
When debugging the code, my model has a value for id
but not for number_Of_ID
. The value is always 0. I've also tried changing the datatype to a string
and it returns null
. Please help.
推荐答案
虽然我无法使用 DBContext
,我发现使用 SQLDataAdapter
的解决方案。即使有空格的列也能成功打电话。控制器中更改了以下内容:
While I was not able to use a DBContext
, I found a solution using SQLDataAdapter
. I was able to make the call successfully even with columns that had spaces. The following was changed in the controller:
MyController.cs
MyController.cs
using System;
...
namespace ...
{
public class MyController : Controller
{
public ActionResult Index()
{
var myResultsList = new List<MyModel>();
string connectionString = ConfigurationManager.AppSettings["myDBConn"];
var conn = new SqlConnection(connectionString);
conn.Open();
string query = @"usp_getIds";
using (var sqlAdpt = new SqlDataAdapter(query, conn))
{
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
var results = new DataSet();
sqlAdpt.Fill(results);
myResultsList= results.Tables[0].AsEnumerable().
Select(dataRow => new MyModel
{
id = dataRow.Field<string>("ID"),
numberOfID = dataRow.Field<int>("Number Of ID")
}).ToList();
}
return View(myResultsList);
}
}
这篇关于如何调用使用空格返回列的存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!