I have a Blazor WASM Core Hosted app that I am trying to setup a one-to-many (optional with the many) using Entity Framework. But this is causing a circular reference error, and I am not sure why. Here is what I have:
Models:
public class Blog { public int Id { get; set; } [Required] public string BlogName{ get; set; } = string.Empty; public ICollection<Post> Posts { get; set; } } public class Post { public int Id { get; set; } public int BlogId{ get; set; } public Blog Blog{ get; set; } }DBContext:
modelBuilder.Entity<Blog>() .HasMany(d => d.Post) .WithOne(o => o.Blog) .HasForeignKey(o => o.BlogId);I then make a call in my controller like this:
[HttpGet("get-blog-with-posts/{blogId}")]public async Task<ActionResult<ServiceResponse<Blog>>> GetBlogWithPosts(int blogId){ var options = await this._blogService.GetBlogWithPosts(blogId); return Ok(options); //loop starts here}and my service looks like this:
public async Task<ServiceResponse<Blog>> GetBlogWithPosts(int blogId){ var blog= await _context.Blog.Include(p => p.Posts).FirstOrDefaultAsync(x => x.Id == blogId); if (blog == null) { return new ServiceResponse<Blog> { Success = false, Message = "Blog Not Found." }; } var response = new ServiceResponse<Blog> { Data = blog, Success = true }; return response;}and my serviceresponse wrapper looks like this:
public class ServiceResponse<T>{ public T? Data { get; set; } public bool Success { get; set; } = false; public string Message { get; set; } = String.Empty;}When this runs, I get in a loop at my controller, when it tries to return the result, where it will go into my ServiceResponse, to the Data, and into the Blog model, then into the Posts and back to the Blog model over and over again until it dies.