我遇到的问题包括通过存储过程从表中显示所有数据。我正在使用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>
答案 0 :(得分:1)
您实际上并没有返回存储过程的值,而是覆盖了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(););
}
答案 1 :(得分:0)
您的模型中存在问题。您从SP加载所有配方,然后在循环中,您尝试将值从结果设置为RecipeModel字段。但是在你的循环中,如果你有下一个配方你正在做下一个:在迭代1中你从配方1获得值并将它们设置为RecipeModel,然后你去迭代2和配方2的所有值再次设置为相同对象RecipeModel已经有来自配方1的值,因此您只需覆盖这些值。
所以你需要从数据库中为每个食谱创建一个单独的RecipeModel。您传递给视图的模型应该是RecipeModel的列表,并且在您的视图中,您应该有foreach循环,它将把配方写入html。
答案 2 :(得分:0)
您在以下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;
}
您需要将每次迭代添加到模型的新实例并返回List
或其他集合类型。
答案 3 :(得分:0)
你有一个RecipeModel
类,你有一个获取所有项目的方法(RecipeModel的集合)。仔细查看您的方法。你是通过集合循环并一次又一次地设置类(一类有效的对象)的特性(覆盖到同一个实例)
理想情况在循环中,您需要创建RecipeModel的实例并设置值并将其添加到RecipeModel的集合中。
我不会在您的Model类中混用此方法。我会把它移到一个单独的类,在那里会有一个返回RecipeModel
类列表的方法。一种Repositary方法。