Using Microsoft.EntityFrameworkCore.InMemory (5.0.0), I have the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using BlogExample;
namespace BlogExample.Data
{
public class BlogsContext : DbContext
{
public BlogsContext (DbContextOptions<BlogsContext> options)
: base(options)
{
}
public DbSet<BlogExample.Blog> Blogs { get; set; }
public DbSet<BlogExample.Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasMany(b => b.Posts)
.WithOne();
modelBuilder.Entity<Blog>()
.Navigation(b => b.Posts)
.UsePropertyAccessMode(PropertyAccessMode.Property);
}
}
}
namespace BlogExample
{
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; }
}
}
Now I have the following controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BlogExample;
using BlogExample.Data;
namespace BlogExample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BlogsController : ControllerBase
{
private readonly BlogsContext _context;
public BlogsController(BlogsContext context)
{
_context = context;
}
// GET: api/Blogs
[HttpGet]
public async Task<ActionResult<IEnumerable<Blog>>> GetBlog()
{
return await _context.Blogs.ToListAsync();
}
// GET: api/Blogs/5
[HttpGet("{id}")]
public async Task<ActionResult<Blog>> GetBlog(int id)
{
var blog = await _context.Blogs.FindAsync(id);
if (blog == null)
{
return NotFound();
}
return blog;
}
// POST: api/Blogs
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Blog>> PostBlog(Blog blog)
{
_context.Blogs.Add(blog);
await _context.SaveChangesAsync();
return CreatedAtAction("GetBlog", new { id = blog.BlogId }, blog);
}
}
}
So, when I POST the following JSON for a blog:
{
"blogId": 1,
"url": "MyUrl",
"posts": [
{
"postId": 1,
"title": "title1",
"content": "content1"
}
]
}
Then if I try to perform the GET call to get all my Blogs, I get the blog I just entered above with the posts list property set to null as shown in the response body below:
[
{
"blogId": 1,
"url": "MyUrl",
"posts": null
}
]
My code can be found here
I am using the following documentation as a reference: