【发布时间】:2025-11-30 10:30:01
【问题描述】:
我在 ASP.NET MVC4 和 CodeFirst 上的关系方面遇到了一些问题,而且这些表的返回值与外键相关。
首先,让我们看看我做的是否正确。
这是我的代码示例:
人物类
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public City City { get; set; }
}
城市类
public class City {
public int Id { get; set; }
public string Name { get; set; }
}
因此,数据库创建了一个漂亮的关系,并且看起来工作得很好。在这段代码之后,我有这样的表格:
人
--Id (PK)
--名称
--姓氏
--City_Id (FK)
城市
--Id (PK)
--名称
我已经用种子填充了这个,这是一个例子:
context.Person.AddOrUpdate(p => p.Name,
new Person { Name = "Me", City = new City { Name = "Ludlow" } }
);
当我需要将信息检索到视图时,像这样......
MyDataBase.cs
public class LeilaoDb : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<City> Cities { get; set; }
}
HomeController.cs
MyDataBase _db = new MyDataBase();
public ActionResult Index()
{
var model = _db.Persons.ToList();
return View(model);
}
Home/Index.cshtml
@model IEnumerable<testingproject.Models.Person>
@{
ViewBag.Title = "Home Page";
}
@foreach (var item in Model)
{
@Html.Partial( "_Person", item );
}
_Person.cshtml
@model testingproject.Models.Person
<div>
<h3>@Model.Name</h3>
@Model.City.Name
</div>
我收到一个空异常...
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
那么,怎么了?
解决方案:
我找到了解决办法,
MyDataBase _db = new MyDataBase();
public ActionResult Index()
{
var model = _db.Persons.ToList();
return View(model);
}
此代码仅检索人员,在不需要建立关系时可能不会超载。您需要使用Include() 方法指定何时需要处理这些关系。
在这之后,就很简单了:
MyDataBase _db = new MyDataBase();
public ActionResult Index()
{
var model = _db.Persons.Include("City");
return View(model);
}
我觉得将字符串传递给这个方法很奇怪,但没关系。如果我真的需要,我现在可以使用 @Model.City.Name 返回我的值。
我在这个网站here找到了解决方案
【问题讨论】:
-
这是因为您明确使用了
Model。如果@model 没有收到任何数据,那么Model将是null。最好使用像@Html.EditorFor(model => model.Name)这样的助手。这会处理null的情况。 -
您是否将模型传递给您的视图?
-
我将一个模型传递给这样的视图:
public ActionResult Index() { var model = _db.Persons.ToList(); return View(model) },在这种情况下我有一个MyDataBase _db = new MyDataBase();,我有一个上下文是MyDataBase.cs,在这个.cs里面,我有这个:public DbSet<Person> Persons { get; set; },public DbSet<City> Cities { get; set; } -
对不起,我还有其他文件是:
@model IEnumerable<testingproject.Models.Leilao>和下面的@foreach (var item in Model) { @Html.Partial( "_Person", item ); }。而且,如果我删除@Model.City.Name,视图会返回人名。 -
似乎可能存在一些歧义,因为您正在为属性名称
City分配一个类的实例City...
标签: asp.net-mvc-4 ef-code-first entity-framework-migrations