【问题标题】:Why do Entity Framework classes need a virtual member of an unrelated class为什么实体框架类需要不相关类的虚拟成员
【发布时间】:2012-06-29 07:59:58
【问题描述】:

通过示例更容易展示——我使用代码优先来构建数据库。我有以下课程:

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

我不明白为什么 Post 需要公共虚拟博客博客。它是否充当数据库中的外键以链接回博客?如果是这种情况,您似乎会使用博客 ID。

【问题讨论】:

  • 如果它是 NHibernate 之类的东西,则需要 virtual 是因为创建了一个动态代理,overrides 成员提供延迟加载功能。

标签: database asp.net-mvc-3 entity-framework ef-code-first


【解决方案1】:

它确实允许两个表关联,并在与Blog 相关的Post 上放置一个外键。

拥有public virtual Blog Blog { get; set; } 允许您从Post 对象引用Blog 对象,然后访问Blog 的所有属性。例如。 myPost.Blog.Id 如果它使用public virtual int BlogId { get; set; },您将无法执行此操作,因为BlogId 将只是一个int 值。

如果您的域对象是 lazy loaded,则在使用该属性之前,myPost.Blog 实际上不会与数据库中的数据相结合(即不调用 Blog 表)。一旦使用它,Entity Framework 就会为您调用数据库,并使用 Blog 表中的数据对对象进行水合。这是使用 ORM 的一部分...它允许您在处理数据库操作的同时专注于代码。

【讨论】:

  • 这实际上有一些有趣的性能影响。如果您知道您将使用您的导航属性,您可以通过禁用延迟加载来获得更好的性能。您无需多次往返数据库,而是进行一次。在您可能只是偶尔(或根本不)使用数据的其他情况下,延迟加载可以帮助降低加载不需要的数据的成本。当然,您应该始终努力做类似select new { your_data_here } 的事情,但这并不总是可行的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 2023-04-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
相关资源
最近更新 更多