EF include 预先加载
在asp.net mvc 中,常在控制器中预先加载导航属性,以便在视图中能够显示起关联的数据。 如果不预先加载,View中就会无法呈现外键的 关联数据。 会提示EF 错误发生。
一、
模型:
public class Department
{
public int DepartmentID { get; set; }
[StringLength(50, MinimumLength = 3),Display(Name="部门名称")]
public string Name { get; set; }
[Display(Name="经费预算")]
[DataType(DataType.Currency)]
[Column(TypeName="money")]
public decimal Budget {get;set;}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString="{0:yyyy-MM-dd}",ApplyFormatInEditMode=true)]
[Display(Name="成立日期")]
public DateTime StartDate { get; set; }
[Display(Name = "负责人")]
public int? InstructorID { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
[Display(Name="负责人")]
public virtual Instructor Admistrator { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
}
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name="课程代码")]
public int CourseID { get; set; }
[Display(Name="课程名称")]
[StringLength(50,MinimumLength=3)]
public string Title { get; set; }
[Display(Name="学分")]
[Range(0,50)]
public int Credits { get; set; }
[Display(Name="部门名称")]
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
控制器调用 :
private SchoolContext db = new SchoolContext();
var courses = db.Courses.Include(c => c.Department); lambda表达式形式。
二、有些情况下,无法使用lambda表达式形式,可以使用字符串形式的Include预先加载。
var categorys =ContextFactory.GetCurrentContext().Categories.Include("Articles").Where(c => c.NavbarIsShow).OrderBy(c => c.PriorOrder);