【问题标题】:Understanding code first virtual properties了解代码优先虚拟属性
【发布时间】:2013-03-06 12:39:30
【问题描述】:

您好,我刚开始学习使用实体框架代码,我似乎无法理解一些东西。我根据教程创建了三个模型:

public class Course
{
    public int CourseID { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public virtual ICollection<Enrollment> Enrollments{ get; set; }
}

public class Enrollment
{
    public int EnrollmentID { get; set; }
    public int CourseID { get; set; }
    public int StudentID { get; set; }
    public decimal? Grade { get; set; }
    public virtual Course Course { get; set; }
    public virtual Student Student { get; set; }
}
public class Student
{
    public int StudentID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

我的问题是我不明白 virtual 的属性是做什么的。如果我检查数据库,每个属性都没有列箱,只有其他的。

那么当您使用 virtual 关键字创建属性时会发生什么?

【问题讨论】:

    标签: c# entity-framework entity-framework-4.1


    【解决方案1】:

    用于管理延迟加载更改跟踪

    EF 将在运行时生成代理类型,这些代理类型是动态生成的类型,它们从您的 POCO 类继承,并添加所有 EF 内容以在被覆盖的虚拟属性中管理延迟加载/更改跟踪

    所以virtual 在这里不是一个“神奇的关键字”,virtual 在这里,因此您的 POCO 可以在运行时通过其他与 EF 相关的代码来继承。

    【讨论】:

      【解决方案2】:

      虚拟属性允许延迟加载

      【讨论】:

        【解决方案3】:

        当您创建一个用 virtual 关键字标记的属性或方法时,您将被允许在派生类中覆盖它,从而根据您创建的对象为您的方法提供更专业的行为。

        在实体框架的情况下,它也是一个指出使用延迟加载行为的约定。这里有一个关于这个问题的问题:Entity Framework 4.1 Virtual Properties

        【讨论】:

        猜你喜欢
        • 2012-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-18
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多