【发布时间】:2014-01-26 10:41:30
【问题描述】:
设置
我有一个相当简单的 3 类设置如下。当然还有很多其他的属性,但是这里不相关。
模型
public class Employee {
public int EmployeeId { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public ICollection<Position> Positions { get; set; }
}
public class Position {
public int PositionId { get; set; }
public int EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public Employee Employee { get; set; }
public int location { get; set; }
[ForeignKey("location")]
public Location Location { get; set; }
}
public class Location {
public int LocationId { get; set; }
public string Name { get; set; }
}
控制器
public ActionResult Index() {
string username = User.Identity.Name;
Employee emp = context.Employees.Include(e => e.Positions).FirstOrDefault(e => e.UserName == username);
return View(emp);
查看
@model Employee
<h1>Hi @Model.Name</h1>
<ul>
@foreach (var position in @Model.Positions) {
<li>@position.Name - @position.Location.Name</li>
}
</ul>
问题
现在的问题是因为延迟加载。我在@item.Location.Name 调用中收到 NullReferenceException。它正在加载位置就好了(foreach 中的项目)。
我尝试将我的包含更改为:
context.Employees.Include("Positions.Location").FirstOrDefault(e => e.UserName == username);
但随后我收到错误消息:元数据集合中有多个项目与身份“位置”匹配。
如果我将Position 上的Location 属性更改为PositionLocation,则会得到:System.Reflection.AmbiguousMatchException: Ambiguous match found。
我是否应该使用一个 ViewModel 来加载多个查询到我的控制器中的上下文?这似乎需要维护更多的代码,如果不需要,我宁愿不要。
【问题讨论】:
-
我想知道您将 Location 类与 Position 类中使用的属性同名这一事实是否存在问题。
-
@Corylulu 尝试将属性更改为“PositionLocation”,现在我得到
System.Reflection.AmbiguousMatchException: Ambiguous match found. -
您确定所有更改都正确吗?您相应地更新了您引用位置的所有实例?好像遗漏了什么。也许编辑整个代码以反映任何新的变化。
-
@Corylulu 我仔细检查过,它仍然给出了那个错误。
标签: asp.net-mvc-4 entity-framework-5