我正在使用http://ef.readthedocs.org/en/latest/getting-started/aspnet5.html中的下面这个例子来测试asp.net 5和EF7:
using Microsoft.Data.Entity;
using System.Collections.Generic;
namespace EFGetStarted.AspNet5.Models
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Make Blog.Url required
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}但在我的测试中
public List<Post> Posts { get; set; }总是空的。这看起来很明显,因为它不是实例化的。
我要做些什么才能得到这样的行为
myBlog.Posts从这个博客上得到所有的帖子?
发布于 2015-09-14 13:29:19
您应该为导航属性指定virtual关键字。这是因为EF创建代理对象(即类的继承者)来实现延迟加载。这些继承者只能重写您的虚拟属性:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}或者,您也可以显式地枚举表/类以(包括)到结果集:
// This statement fills Posts property:
var blog = dbContext.Blogs.Include(x => x.Posts).FirstOrDefault(x => x.Id == id);https://stackoverflow.com/questions/32566077
复制相似问题