我有一个相当简单的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中的项目)。
我尝试将我的Include改为:
context.Employees.Include("Positions.Location").FirstOrDefault(e => e.UserName == username);
但后来我收到错误:元数据集合中的多个项目与“位置”标识相匹配。
如果我将Location
上的Position
属性更改为PositionLocation
,则会收到: System.Reflection.AmbiguousMatchException:找到不明确的匹配。
我是否应该使用我在控制器中加载多个查询到我的上下文的ViewModel?这似乎要维护更多的代码,如果我不需要,我宁愿不去。
答案 0 :(得分:0)
原来这是因为当你有一个导航属性并且它的外键只是大小写时,EF不喜欢它。如果您的模型中有一个ANYWHERE,即使您在当前请求中未对此属性进行引用,也会出现此错误。
将导致AmbiguousMatchException的示例:
public int location {get;set;}
[ForeignKey("location")]
public Location Location {get;set;}
工作正常的示例:
public int locationid {get;set;}
[ForeignKey("locationid")]
public Location Location {get;set;}