C# 当我在EF中使用多对多关系时,如何在视图中显示配方中的所有成分?
所以我想在一个视图中显示一个食谱包含的所有成分。我用EF创建了一个配料表和一个配方表。这种关系是多对多的。我不知道如何在一个视图中显示食谱的成分 我试图修改模型,以便显示成分,但我只能看到一种成分 这是我的配料课:C# 当我在EF中使用多对多关系时,如何在视图中显示配方中的所有成分?,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,所以我想在一个视图中显示一个食谱包含的所有成分。我用EF创建了一个配料表和一个配方表。这种关系是多对多的。我不知道如何在一个视图中显示食谱的成分 我试图修改模型,以便显示成分,但我只能看到一种成分 这是我的配料课: namespace Licenta.Models { public class Ingredient { [Key] public int IDIngredient { get; set; } public string
namespace Licenta.Models
{
public class Ingredient
{
[Key]
public int IDIngredient { get; set; }
public string Nume { get; set; }
public int Kcal { get; set; }
public int Pro { get; set; }
public int Carbo { get; set; }
public int Fat { get; set; }
public IList<Recipe> Recipes { get; set; }
}
}
我还看到EF在我的数据库中创建了一个RecipesComponents表。我应该如何使用该表列出我配方的成分?在数据库外查询配方成分时,需要包括配方成分 i、 e:替换
db.Recipes.Find(id)代码>
与
db.Recipes.Include(x=>x.components)。Single(y=>y.Id==Id)代码>
要显示成分详细信息,您需要循环查看成分,并显示每个成分中您想要的任何数据
i、 e:替换
<dd>
@Html.DisplayFor(model => model.Ingredients)
</dd>
您还可以创建一个以IList
为模型的显示模板。如果您这样做了,您将根本不需要更改当前的模型,因为DisplayFor
将自动查找要使用的显示模板。如果您在返回视图(配方)
上设置断点,则是配方。配料
null?显然是。即使我在我的Recipes配料表中创建了一行,指定ID为1的配方应包含ID为1的配料,如果您更改db.Recipes.Find(ID),该怎么办
到db.Recipes.Include(y=>y.components).Single(x=>x.Id==Id)
它给了我这个错误:“无法将lambda表达式转换为'string'类型,因为它不是委托类型”。请使用System.Linq包含代码>和使用System.Data.Entity代码>在你的班级中名列前茅
@model Licenta.Models.Recipe
@{
ViewBag.Title = "Details";
}
<h2>Recipe Details</h2>
<div>
<h4>Recipe</h4>
<hr />
<dl class="dl-horizontal">
<dt>
Name:
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
Calories:
</dt>
<dd>
@Html.DisplayFor(model => model.Kcal) calorii
</dd>
<dt>
Proteins:
</dt>
<dd>
@Html.DisplayFor(model => model.Pro) grame
</dd>
<dt>
Carbs:
</dt>
<dd>
@Html.DisplayFor(model => model.Carbo) grame
</dd>
<dt>
Fat:
</dt>
<dd>
@Html.DisplayFor(model => model.Fat) grame
</dd>
<dt>
Description:
</dt>
<dd>
@Html.DisplayFor(model => model.Desc)
</dd>
<dt>
Steps:
</dt>
<dd>
@Html.DisplayFor(model => model.Steps)
</dd>
<dt>
Ingredients:
</dt>
<dd>
@Html.DisplayFor(model => model.Ingredients)
</dd>
</dl>
</div>
namespace Licenta.Controllers
{
public class HomeController : Controller
{
private DataContext db = new DataContext();
public ActionResult Index()
{
return View();
}
public ActionResult Recipes()
{
return View(db.Recipes.ToList());
}
public ActionResult Details(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Recipe recipe = db.Recipes.Find(id);
if(recipe == null)
{
return HttpNotFound();
}
return View(recipe);
}
}
}
<dd>
@Html.DisplayFor(model => model.Ingredients)
</dd>
@foreach(var ingredient in Model.Ingredients)
{
/*feel free to format/display this however you want.
this is only intended to show you how to accomplish
what you're asking*/
Nume: @ingredient.Nume
Carbo: @ingredient.Carbo
Pro: @ingredient.Pro
}