zoukankan      html  css  js  c++  java
  • 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);

  • 相关阅读:
    POJ
    hdu 5652
    CodeForces
    #6285. 数列分块入门 9
    #6284. 数列分块入门 8
    #6283. 数列分块入门 7
    #6282. 数列分块入门 6
    #6280. 数列分块入门 4 #6281. 数列分块入门 5
    #6278. 数列分块入门 2和#6278. 数列分块入门 3
    spark-sklearn TypeError: 'JavaPackage' object is not callable
  • 原文地址:https://www.cnblogs.com/liuyuanhao/p/4486464.html
Copyright © 2011-2022 走看看