Search code examples
c#asp.net-core-mvcasp.net-core-6.0

ASP.NET Core 6 MVC / C# : one-to-many get data from many side


I am trying to access the data on the many side of a one to many relationship. In the Index action of my controller I assign the data to a variable and return it. I have a Blog, the one side, with many posts. I just want to list the blogs with their posts in the view.

For example...

Blog1
    post1
    post2
    post3
Blog2
    post1
    post2

That's pretty much it. But as it stands, in the view, I am unable to access the post data.

Here are my models with the relevant properties

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Post>? Posts { get; set; } = new HashSet<Post>();
}

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int BlogId { get; set; }
}

And here is the controller

public async Task<IActionResult> Index()
{
    var applicationDbContext = _context.Blogs
            .Include(b => b.BlogUsers)
            .Include(p => p.Posts)
            .ToListAsync();

    return View(await applicationDbContext);
}

I've included the Posts so I should be able to access the Post data. I can access the Blogs data no problem.

Any ideas?


Solution

  • If you want to get Posts you can try:

    public async Task<IActionResult> Index()
            {
                 var applicationDbContext = await _context.Blogs
                  .Include(b => b.BlogUsers)
                  .Include(p => p.Posts)
                  .ToListAsync();
                return View(applicationDbContext);
            }
    

    If you want @item.Posts., the properties appear in the intellisence after the dot. You need to use

    public virtual Post? Posts { get; set; }
    

    Because ICollection<Post> don't have a definition for Id. We define the Id in the Post .

    For example I was hoping that @item.Posts.Title would work,

    Try:

    @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)                 
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
           @* @item.Posts.Id*@
                @foreach (var item2 in item.Posts)
                {
                     @item2.Title
                }
            }