简体   繁体   English

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

[英]Cannot persist lists in entities when using Entity Framework Core

Using Microsoft.EntityFrameworkCore.InMemory (5.0.0), I have the following code:使用 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; }
    }
}

Now I have the following controller:现在我有以下 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:因此,当我为博客发布以下 JSON 时:

{
  "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:然后,如果我尝试执行 GET 调用来获取我的所有博客,我会得到我刚刚在上面输入的博客,其帖子列表属性设置为 null,如下面的响应正文所示:

[
  {
    "blogId": 1,
    "url": "MyUrl",
    "posts": null
  }
]

My code can be found here我的代码可以在这里找到

I am using the following documentation as a reference:我使用以下文档作为参考:

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

You need to request that EF include related entities.您需要请求 EF 包含相关实体。 Otherwise fetching a single Entity could end up bringing the whole database back.否则,获取单个实体最终可能会带回整个数据库。

Should be应该

// GET: api/Blogs
[HttpGet]
public async Task<ActionResult<IEnumerable<Blog>>> GetBlogs()
{
    return await _context.Blogs
                         .Include(blog => blog.Posts)
                         .ToListAsync();
}

See

Eager loading渴望加载

You can use the Include method to specify related data to be included in query results.您可以使用 Include 方法指定要包含在查询结果中的相关数据。 In the following example, the blogs that are returned in the results will have their Posts property populated with the related posts.在以下示例中,结果中返回的博客将使用相关帖子填充其 Posts 属性。

Eager Loading of Related Data 急切加载相关数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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