【发布时间】:2013-09-13 17:51:07
【问题描述】:
我正在开发一个多层的 ASP.NET MVC Web 应用程序,但由于无法在我的应用程序中检索我的数据的准确对象表示,因此无法取得进一步进展。 为什么会这样?我已尽量详细说明,但如果您想了解更多信息,请要求澄清。我的项目如下:
-MyProject.Data
-MyProject.Logic
-MyProject.Objects
-MyProject.Web
我的实体类来自 MyProject.Objects.Entities
public class Report
{
[Key]
public int Id { get; set; }
public string ReportName { get; set; }
public int ProductId { get; set; }
}
public class Product
{
[Key]
public int Id { get; set; }
public string ProductName { get; set; }
public ICollection<Report> ProductReports { get; set; }
}
来自 MyProject.Data
的我的上下文public class MyDb : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Report> Reports { get; set; }
}
我的控制器来自 MyProject.Web
public class HomeController : Controller
{
MyDb _db = new MyDb();
public ActionResult Index()
{
var model =
from p in _db.Products
orderby p.ProductName ascending
select p;
return View(model);
}
}
最后,我的 Seed() 方法来自 MyProject.Data.Migrations.Configuration
protected override void Seed(MyProject.Data.MyDb context)
{
context.Products.AddOrUpdate(r => r.ProductName,
new Product
{
ProductName = "AAA",
ProductReports =
new List<Report> {
new Report { ReportName = "Report A" },
new Report { ReportName = "Report B" },
new Report { ReportName = "Report C" }
}
},
new Product
{
ProductName = "MSI",
ProductReports =
new List<Report> {
new Report { ReportName = "Report X" },
new Report { ReportName = "Report Z" }
}
});
}
我不知道为什么我无法从 MyProject.Objects.Entities.Product 获取ICollection<Report> ProductReports 以填充正确的值。这是我在 MyProject.Web
Index() 的结果
起初我对这个框架有点陌生,我认为我遇到了一些与数据结构相关的问题。据我所知,我的数据似乎设置正确。这是我在 SQL Server 中的数据
为了进一步证明数据似乎是正确的,我运行了以下查询以确保关系设置正确。我将在查询旁边提供结果。
SELECT * From Reports INNER JOIN Products ON Reports.ProductId = Products.Id
【问题讨论】:
-
看起来您实际上从未定义过两个实体之间的映射。没有那个代码吗?
-
也许吧。我的项目中没有任何类型的映射代码。我还没有看到这样的例子。我会调查一下,谢谢@wilso132
标签: c# .net asp.net-mvc entity-framework n-tier-architecture