[英]Cannot persist lists in entities when using Entity Framework Core
使用 Microsoft.EntityFrameworkCore.InMemory (5.0.0),我有以下代碼:
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; }
}
}
現在我有以下 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);
}
}
}
因此,當我為博客發布以下 JSON 時:
{
"blogId": 1,
"url": "MyUrl",
"posts": [
{
"postId": 1,
"title": "title1",
"content": "content1"
}
]
}
然后,如果我嘗試執行 GET 調用來獲取我的所有博客,我會得到我剛剛在上面輸入的博客,其帖子列表屬性設置為 null,如下面的響應正文所示:
[
{
"blogId": 1,
"url": "MyUrl",
"posts": null
}
]
我的代碼可以在這里找到
我使用以下文檔作為參考:
您需要請求 EF 包含相關實體。 否則,獲取單個實體最終可能會帶回整個數據庫。
應該
// GET: api/Blogs
[HttpGet]
public async Task<ActionResult<IEnumerable<Blog>>> GetBlogs()
{
return await _context.Blogs
.Include(blog => blog.Posts)
.ToListAsync();
}
看
渴望加載
您可以使用 Include 方法指定要包含在查詢結果中的相關數據。 在以下示例中,結果中返回的博客將使用相關帖子填充其 Posts 屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.