[英]C# (MVC3) Stored Procedure LINQ SQL
我有一个问题,其中包括通过存储过程显示表中的所有数据。 我正在使用LINQ访问我的存储过程,但事实是,我的结果(显示的数据)只是表中的最后一行。 我无法正常工作...如果有人可以帮助我/解释我做错了什么,我将深表感谢。
型号: RecipeModel
模型
public class RecipeModel
{
.....
public void GetAllRecipes()
{
DataClassesDataContext db = new DataClassesDataContext();
var result = db.p_get_all_recipes();
foreach (var r in result)
{
this.recipeName = r.name;
this.recipeDescription = r.description;
this.recipeSteps = r.steps;
this.createdAt = r.createdAt;
this.updatedAt = r.updatedAt;
this.ownerID = r.owner_id;
}
}
控制器 : RecipeController
public class RecipeController : Controller
{
[HttpGet]
public ActionResult Index()
{
RecipeModel rec = new RecipeModel();
rec.GetAllRecipes();
return View(rec);
}
视图(剃刀) : Index
@model MVC3_LINQ_SP.Models.RecipeModel
@{
ViewBag.Title = "Index";
}
<legend>Recipe </legend>
<p>@Html.DisplayFor(model => model.rName)</p>
您实际上并没有返回存储过程的值,而是覆盖了RecipeModel
的属性。
您应该创建一个Recipe类来保存存储过程的返回值:
public class Recipe
{
public string recipeName { get; set; }
public string recipeDescription { get; set; }
public string recipeSteps { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public DateTime ownerID { get; set; }
}
然后更改您的过程以完成此操作-我假设db.p_get_all_recipes()返回的是可查询的列表:
public IQueryable<Recipe> GetAllRecipes()
{
DataClassesDataContext db = new DataClassesDataContext();
return db.p_get_all_recipes().Select(r => new Recipe()
{
recipeName = r.name;
recipeDescription = r.description;
recipeSteps = r.steps;
createdAt = r.createdAt;
updatedAt = r.updatedAt;
ownerID = r.owner_id;
});
}
然后,您需要更改视图:
@model IQueryable<Recipe>
和您的控制器动作:
[HttpGet]
public ActionResult Index()
{
RecipeModel rec = new RecipeModel();
return View( rec.GetAllRecipes(););
}
您的模型有问题。 您可以从SP加载所有配方,然后在周期中尝试将结果中的值设置为RecipeModel字段。 但是在您的周期中,如果您有多个配方,则接下来要执行的操作:在迭代1中,您从配方1中获取值并将其设置为RecipeModel,然后转到迭代2中,并再次将配方2中的所有值都设置为相同对象RecipeModel已经具有配方1中的值,因此您只需覆盖这些值。
因此,您需要为每个配方数据库创建一个单独的RecipeModel。 您要传递给视图的模型应该是RecipeModels的列表,并且在View中应该有foreach周期,该周期将配方写入html。
您在以下for循环中覆盖了局部变量:
foreach (var r in result)
{
this.recipeName = r.name;
this.recipeDescription = r.description;
this.recipeSteps = r.steps;
this.createdAt = r.createdAt;
this.updatedAt = r.updatedAt;
this.ownerID = r.owner_id;
}
您需要将每个迭代添加到Model的新实例中,并返回List
或其他集合类型。
您有一个RecipeModel
类,在其中有一个获取所有项目的方法(RecipeModel的集合)。 仔细查看您的方法。 您正在遍历集合并一次又一次地设置Class(属性的对象)的属性(覆盖同一实例)
理想情况下,在循环中,您需要创建RecipeModel的实例并设置值并将其添加到RecipeModel的集合中。
我不会在您的Model类中混合使用此方法。 我将其移至一个单独的类,在该类中将有一种方法可以返回RecipeModel
类的列表。 存储库方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.