[英]Return Parameterized Query Results with MVC and EF
I am trying to use Visual Studio 2013, MVC and Entity Framework to return results of a stored proc to display data to a user. 我正在尝试使用Visual Studio 2013,MVC和实体框架返回存储过程的结果以向用户显示数据。 I've already added the EDMX model to my solution and completed the Function Import Wizard for the stored procedure I am looking to execute.
我已经将EDMX模型添加到我的解决方案中,并为要执行的存储过程完成了功能导入向导。 What I am stuck on is how to code the Model and Controller and return the data to the View.
我所坚持的是如何对模型和控制器进行编码并将数据返回到视图。 I don't want to use the generated CRUD operations and scaffolded views EF creates.
我不想使用EF创建的生成的CRUD操作和支架视图。
Stored Proc : 存储过程 :
SELECT C.ClassName, G.Grade
FROM Classes as C
INNER JOIN Grade as G on C.ClassID = G.ClassID
WHERE C.UserID = @UserID
Model : 型号 :
public class TestModel
{
public string ClassName {get; set;}
public string Grade{get;set;}
}
Controller : 控制器 :
public class TestController : Controller{
public ActionResult Index()
{
TestEntities db = new TestEntities();
var result = db.TestEntities ("@username");
ViewBag.Results = result.ToList();
return View(result.ToList());
}
}
View : 查看 :
<table>
<h>ViewBag.Results.ClassName</h>
<h>ViewBag.Results.Grade</h>
</table>
This is just the simple code. 这只是简单的代码。 My references are all in tact.
我的参考资料完好无损。
If you already map the stored procedure in your EDMX, you must have a method like this on your context: 如果您已经在EDMX中映射了存储过程,则必须在上下文中使用如下方法:
[DbFunction("TestEntities", "YourStoreProcedureName")]
public virtual IQueryable<TestModel> YourStoreProcedureName(int UserID)
{
var userIDParameter = UserID != 0?
new ObjectParameter("UserID", UserId) :
new ObjectParameter("UserID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<TestModel>("[TestEntities].[YourStoreProcedureName](@UserId)", userIDParameter);
}
So, you can call it from your context this way: 因此,您可以通过以下方式从上下文中调用它:
TestEntities db = new TestEntities();
var result = db.YourStoreProcedureName(1).ToList();
Check this page to see more details about this. 检查此页面以查看有关此的更多详细信息。
Now, if you want to call a parametrized query using EF, you can do it as I show below: 现在,如果要使用EF调用参数化查询,可以按照以下所示操作:
var query =String.Format( @"SELECT C.ClassName, G.Grade
FROM Classes as C
INNER JOIN Grade as G on C.ClassID = G.ClassID
WHERE C.UserID = {0}",UserId);
TestEntities db = new TestEntities();
var result = db.Database.SqlQuery<TestModel>(query).ToList();
And, if you want to call a stored procedure that is not mapped in your EDMX, you can call it this way: 而且,如果您要调用未在EDMX中映射的存储过程,则可以通过以下方式调用它:
TestEntities db = new TestEntities();
var result = db.Database.SqlQuery<TestModel>("YourStoreProcedureName", new SqlParameter("UserId",1)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.