为什么Entity Framework类需要一个不相关类的虚拟成员

Nic*_*own 4 database entity-framework ef-code-first asp.net-mvc-3

通过示例更容易显示 - 我正在使用代码优先构建数据库.我有以下课程:

public class Blog
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string AuthorName { get; set; }
        public List<Post> Posts { get; set; }
        public string BlogCode
        {
            get
            {
                return Title.Substring(0, 1) + ":" + AuthorName.Substring(0, 1);
            }
        }
    }

    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public virtual Blog Blog { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我不明白为什么Post需要一个公共虚拟博客博客.它是否在数据库中充当外键以链接回Blog?看起来如果是这种情况你会使用Blog Id.

Kev*_*mey 8

它确实允许两个表相关并将外键放在Post相关的表上Blog.

public virtual Blog Blog { get; set; }让你引用Blog从一个对象Post对象,然后得到的所有属性的访问Blog.例如,myPost.Blog.Id 如果使用它public virtual int BlogId { get; set; },你将无法做到这一点,因为它BlogId只是一个int值.

如果你的域对象是延迟加载的,那么在使用该属性之前,myPost.Blog实际上不会使用来自数据库的数据(即不调用Blog表)来补充.一旦使用它,Entity Framework将为您调用数据库,并使用Blog表中的数据来保存对象.这是使用ORM的一部分......它允许您在处理数据库操作时专注于代码.