延迟加载有两个导航属性

时间:2013-02-26 01:15:38

标签: asp.net-mvc-4 entity-framework-5

设置

我有一个相当简单的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?这似乎要维护更多的代码,如果我不需要,我宁愿不去。

1 个答案:

答案 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;}