我试图了解模型如何在。net核心工作,我遇到以下问题:我有一个模型叫做blog:
public class Blog
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Title is required")]
[StringLength(40)]
public string Title { get; set; }
[Required(ErrorMessage = "Date is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "Image is required")]
public string Image { get; set; }
[Required(ErrorMessage = "Description is required")]
[StringLength(400)]
public string Description { get; set; }
public virtual IList<Paragraph> Paragraphs { get; set; } = new List<Paragraph>();
[Required(ErrorMessage = "IsActive is required")]
public bool IsActive { get; set; }
[Required]
public int? CompanyId { get; set; }
public Company Company { get; set; }
public Blog(){}
}
和段落模型:
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Section is required")]
public string Section { get; set;}
[Required]
public int? BlogId { get; set; }
public Blog Blog { get; set; }
public Paragraph()
{
}
当执行应该从这个博客中获取数据的方法时,它返回空段落列表
[HttpGet]
[Route("api/[controller]/{id}")]
public IActionResult GetById(int id)
{
var findBlog = _db.Blog.Find(id);
if (findBlog == null)
{
return NotFound("Blog not found");
}
return new JsonResult(findBlog);
}
反应:
{
"id": 6,
"title": "Test List",
"date": "2021-10-28T00:00:00",
"image": "https://images.pexels.com/photos/2489/street-building-construction-industry.jpg?auto=compress&cs=tinysrgb&dpr=2&w=500",
"description": "Desc",
"paragraphs": [],
"isActive": true,
"companyId": 1,
"company": null
}
您可以尝试使用.Inclue()
包含以下相关数据:
using Microsoft.EntityFrameworkCore;
var findBlog = _db.Blog.Include(a => a.Paragraphs).First(a => a.Id == id);
// all these ways can work well
//var findBlog = _db.Blog.Include(a => a.Paragraphs).Where(a => a.Id == id).ToList();
//var findBlog = _db.Blog.Include(a => a.Paragraphs).FirstOrDefault(a => a.Id == id);
参考:
相关数据的主动加载
我想你正在使用实体框架核心。然后需要使用include
函数加载相关数据。
为示例
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.Include(blog => blog.Owner)
.ToList();
}
适合你的情况
await _dbContext.Blogs
.Include(blog => blog.Paragraphs)
.FirstOrDefaultAsync(blog => blog.Id == id);
要实现这一点,您需要在实体之间建立适当的关系。
见此处的SchoolContext