【发布时间】:2020-11-25 15:28:15
【问题描述】:
使用 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; }
}
}
现在我有以下控制器:
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
}
]
我的代码可以找到here
我使用以下文档作为参考:
【问题讨论】:
-
我克隆了你的仓库,它运行良好。添加一个 Posts 控制器,您会看到在发布博客后您可以获取帖子。
-
是的,我可以获取帖子,但是当我获取博客时,返回的博客的帖子属性仍然为空。但现在我想我知道现在该去哪里找了。这种行为清楚地表明我的 DbContext 正在工作。我只是在检索数据时做错了。
-
必须请求 EF 加载相关实体。阅读:docs.microsoft.com/en-us/ef/core/querying/related-data/eager
-
是的。解决了它。我刚刚添加了 .Include(blog => blog.Posts)。非常感谢!我真的不能感谢你!我们可以将您的最后评论作为这个问题的答案吗?
标签: c# .net entity-framework