Entity Framework Core API return table with .Include

.net-core api entity-framework-core rest

Question

I have a Model with ICollection:

public class Blog
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<Posts> Posts { get; set; }
}

This works with MVC:

public async Task<IActionResult> Index()
{
    return View(await _context.Blog.Include(l => l.Posts).ToListAsync());
}

I try to use API-Controller:

[Route("api/[controller]")]
[ApiController]
....
[HttpGet]
public IEnumerable<Blog> GetAll()
{
    return _context.Blog.Include(l => l.Posts).ToList();
}

This generate a error:

SyntaxError: JSON.parse: end of data after property value in object at line 1 column 44 of the JSON data

How to return a multidimensional Json with Blogs and for every Blog entry all Posts?

1
1
8/30/2018 9:17:51 PM

Accepted Answer

Solution:

This is a error in JSON serialization.

Add in Startup.cs to Mvc ConfigureServices:

services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
2
9/1/2018 12:15:16 PM

Popular Answer

Try this

[Route("api/[controller]")]
[ApiController]
 ....
[HttpGet]
public IActionResult GetAll()
{
   return Ok(_context.Blog.Include(l => l.Posts).ToList());
}

If you try async wrap IActionResult in Task



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow