I´m using the example bellow, from http://ef.readthedocs.org/en/latest/getting-started/aspnet5.html, to test asp.net 5 and 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; }
}
}
But in my test, the
public List<Post> Posts { get; set; }
is always null. This look to be obvious because it is not instantiate.
What I have to do to get a behavior like
myBlog.Posts
and get all the posts from this blog ?
You should specify the virtual keyword for navigation properties. It's because EF creates proxy objects (i.e. inheritors of your classes) to implement lazy-loading. These inheritors can override your virtual properties only:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}
Alternatively you can explicitly enumerate tables/classes to include to result set:
// This statement fills Posts property:
var blog = dbContext.Blogs.Include(x => x.Posts).FirstOrDefault(x => x.Id == id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With