I'm learning Blazor, and creating a website with a simple image viewer.
I have the following classes describing an Image and any Tags that are related:
public class GalleryImage
{
public int ID { get; set; }
public string FileName { get; set; }
public virtual ICollection<GalleryImageTag> ImageTags { get; set; }
}
public class GalleryImageTag
{
public int ID { get; set; }
public string Tag { get; set; }
public virtual ICollection<GalleryImage> GalleryImages { get; set; }
}
As you can see they describe a many-to-many relationship.
In my Controller I have:
[HttpGet("GetGallery")]
public async Task<IActionResult> GetGallery()
{
List<GalleryImage> galleryImagesDB = await _context.GalleryImages
//.Include(a => a.ImageTags)
.ToListAsync();
return Ok(galleryImagesDB);
}
My Blazor page has:
private List<GalleryImage> galleryImages = new();
protected override async Task OnInitializedAsync()
{
try
{
galleryImages = await Http.GetFromJsonAsync<List<GalleryImage>>("api/Gallery/GetGallery");
}
catch (Exception ex)
{
Console.WriteLine($"Error in Gallery.OnInitializedAsync : {ex.Message}");
}
}
This works fine to retrieve a List of GalleryImages from the database. However, when I uncomment the line
.Include(a => a.ImageTags)
then it fails. If I break at the return then galleryImages correctly contains a List of GalleryImages, and any that have been Tagged include a List of GalleryImageTags. But I get an error in the Chrome console:
Error in Gallery.OnInitializedAsync: Response status code does not indicate success: 500 (Internal Server Error).
What am I doing wrong?
Client and Server are both using.Net 5.0.
You have a circular reference. This will return from the DB but will cause the serialisation error. You can put [JsonIgnore]
attribute on one of the collections to prevent to circular serialisation.
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.