【发布时间】:2019-11-29 13:11:03
【问题描述】:
我是 EF 的绝对初学者,我被困在可能非常简单的事情上。
我有 2 个表/类: 玩具和品牌
public class Toys
{
public int Id { get; set; }
public string Name { get; set; }
public int BrandId { get; set; }
}
public class Brands
{
public int BrandId { get; set; }
public string BrandName { get; set; }
}
我的 DBContext 文件:
public class SOT : DbContext
{ public SOT(): base("name=SOT")
{
public virtual DbSet<Brands> brands; set; }
public virtual DbSet<Toys> toys { get; set; }
}
当我添加一条记录时,BrandId 会转到 Toys 表中的 BrandId 字段。
我想在视图中显示玩具名称和品牌名称。现在我得到玩具名称和品牌 ID
在我的控制器中,在索引操作上:
public ViewResult Index()
{
/// this is where I am sooo stuck.....
var toy = _context.Toys.Include(c => c.Brands).ToList();
return View(toy);
}
观点:
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.BrandName)
</td>
我做错了什么?
【问题讨论】:
-
您没有添加任何关系。
Toy(不是玩具,它不是表格或值列表)应该有一个Brand属性。这样您就可以使用item.Brand.BrandName显示品牌名称 -
@PanagiotisKanavos:是的,你是对的。添加品牌属性可以在视图中显示品牌名称。但是,当我现在输入一条新记录时,在 Toys 表中输入了 BrandId int,但引用 Brand 的(新)字段仍然为空。我可以手动选择表中的条目,然后在视图中看到该结果。执行 _context.Toys.Add 显示带有值的 Id,但 Brandfield 为空。有什么建议吗?
标签: entity-framework