I am trying to understand how models work in .net core and I run into the following problem: I have a model called 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(){}
}
And the paragraph model:
[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()
{
}
And when executing the method that should bring me the data from this blog, it returns the list of empty paragraphs
[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);
}
The response:
{
"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
}
CodePudding user response:
I suppose you are using Entity Framework Core. Then you need to load related data using include
function.
for an example
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.Include(blog => blog.Owner)
.ToList();
}
for your case
await _dbContext.Blogs
.Include(blog => blog.Paragraphs)
.FirstOrDefaultAsync(blog => blog.Id == id);
And to achieve this, you need to have proper relationships between entities.
See the SchoolContext here
CodePudding user response:
You can try to use .Inclue()
to include the related data like below:
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);
Reference: