abcde
abcde

Reputation: 23

Return view of a list from EF mapped class in ASP.NET MVC Core

I use ASP.NET MVC Core with EF 1.1.0 and LocalDB and try to search for a blog id (given from url GET) and then send to view the blog's posts list.

Most of the code is taken from microsoft docs examples.

DB Context:

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

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

Controller:

public class BlogsController : Controller
{
    private readonly BloggingContext _context;

    public BlogsController(BloggingContext context)
    {
        _context = context;    
    }

    // GET: Blogs/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var blog = await _context.Blogs
            .SingleOrDefaultAsync(m => m.BlogId == id);
        if (blog == null)
        {
            return NotFound();
        }

        return View(blog.Posts); // HERE IS PROBABLY THE PROBLEM
    }
}

View:

@model IEnumerable<EFGetStarted.AspNetCore.NewDb.Models.Post>

<h2>Details</h2>

<table>

@foreach (var item in Model) {
    <tr>
        <td>
            @item.Title
        </td>
    </tr>
}

</table>

and I get an empty table.. can anyone help?

Thanks.

Upvotes: 0

Views: 1661

Answers (1)

Rick Hodder
Rick Hodder

Reputation: 2252

You need to use Include to make sure that your query pulls in the related Posts for the blog.

 var blog = await _context.Blogs
            .SingleOrDefaultAsync(m => m.BlogId == id);

must be changed to

var blog = await _context.Blogs.Include("Posts")
            .SingleOrDefaultAsync(m => m.BlogId == id);

Upvotes: 2

Related Questions