【发布时间】:2020-09-27 08:19:07
【问题描述】:
我正在尝试在索引页面上获取项目列表 - 但我不断收到错误消息。我尝试了不同的代码,下面是我尝试过的最新代码 - 但它仍然无法正常工作。它给了我这个错误:
System.InvalidOperationException:指定的包含路径无效。 EntityType 'StoreWeb.Models.Project' 没有声明名为 'Collections' 的导航属性
我认为这是因为我不知道如何从 Project 表中获取 collectionID。对于 Project 表,它有 collectionID 作为外键。 (一个项目必须有 1 个集合。一个集合可能有项目。)
有人可以帮帮我吗?这是我所拥有的:
模型
Collection.cs [修改]
[Table("Collection")]
public class Collection
{
[Key]
public string collectionID { get; set; }
public string collectionName { get; set; }
public List<Project> Projects { get; set; }
}
Project.cs [修改]
[Table("Project")]
public class Project
{
[Key]
public string projectID { get; set; }
public string projectName { get; set; }
public string projectCity { get; set; }
public string collectionID { get; set; } // This is what was needed!
public virtual Collection Collection { get; set; }
}
对于项目类,它有collectionID 作为外键。 (一个项目必须有 1 个集合。一个集合可能有项目。)
ProductEntities.cs
public class ProductEntities : DbContext
{
public DbSet<Collection> Collections { get; set; }
public DbSet<Project> Projects { get; set; }
}
控制器
ProjectController [修改]
using System.Data.Entity;
public class ProjectController : Controller
{
ProductEntities productDB = new ProductEntities();
//
// GET: /Project/
public ActionResult Index()
{
var projectModel = productDB.Projects.Include(m => m.Collection);
return View(projectModel);
}
观看次数
Views/Project/Index.chtml
@model IEnumerable<StoreWeb.Models.Project>
@{
ViewBag.Title = "Index";
}
<h1>PROJECTS</h1>
@foreach (var project in Model)
{
<br /><a href="@Url.Action("Details", new { id = project.projectID })">@project.projectName</a>
}
【问题讨论】:
标签: c# asp.net-mvc model-view-controller