我試圖了解模型在 .net core 中的作業方式,但遇到了以下問題:我有一個名為 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
}
uj5u.com熱心網友回復:
我想您正在使用 Entity Framework Core。然后你需要使用函式加載相關資料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
uj5u.com熱心網友回復:
您可以嘗試使用.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);
參考:
急切加載相關資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341464.html
標籤:asp.net 。网 asp.net核心 .net核心
