简体   繁体   中英

How to return a relational data from DB in ASP.Net Core Web API Controller

I have 3 relational table

1-Posts, 2-Comments, 3-Images

"Comments" and "Images" tables have "posts" Foreign Key. I want to return complete information about a post from all tables together in an ASP.Net Core Web API with GET Method. I know how to create controller and such things. My problem is about retrieving and returning data.

If you are using the EFCore , you can do this.

  • Create an ApiController
  • Inject your DbContext from Constructor
  • Read data from DB
  • Return data
[Route("api/[controller]")]
[ApiController]
public class PostController : BaseController
{
    private readonly ApplicationDbContext _dbContext;//Your DbContext
    public PostController(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    [HttpGet]
    public IActionResult Get()
    {
        var data = _dbContext.Post.Include(a=> a.Comments).Include(a=> a.Images).ToList();
        return Ok(data);
    }

}

In .Net Core Lazy loading is disable and when you select a table from database none relation loaded by default.

If you want get all data with relations you must use Include to load relations like this

dbContext.Post.Include(a=> a.Comments).Include(a=> a.Images).ToList();

your database tables should be like this

public class Post
{
    public ICollection<Images> Images { get; set; }
    public ICollection<Comments> Comments { get; set; }
}
public class Comments
{
    public Post Post { get; set; }
}
public class Images
{
    public Post Post { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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