繁体   English   中英

使用 Entity Framework Core 时无法在实体中保留列表

[英]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
  }
]

我的代码可以在这里找到

我使用以下文档作为参考:

https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#single-navigation-property-1

您需要请求 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM