Display many-to-many table data using view model in controller in ASP.NET Core MVC
I want to display many-to-many table data using a view model in controller but I get this error:
CS0029: Cannot implicitly convert type 'Website.Model.PostModel' to 'System.Collections.GenericList<Website.Model.PostModel>'Model: ViewModel: Controller: View: When the controller is used without view model, it works without error. Example:
7 Replies
You defined PostCard on your view model as being a List<PostModel>?
But you are trying to assign the value to a single PostModel element when you use the .SingleAsync method in your controller.
@z0mb I tried using
.ToListAsync()
method but the code gives error regardless.
Here is what I tried:
or
They give server errors!As in it's blowing up when you run the app?
What's the exception? Try wrapping your logic in a try catch block and logging the exception
Sounds like the compile issue was solved, so that's some progress.
I apologize, but I don't know to use try catch block.
The exceptions only appear when I try to open the specific page. Here are the exceptions:
When using
.ThenInclude().ThenInclude().ToListAsync()
:
InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Query.NavigationBaseIncludeIgnored': The navigation 'PostTagModel.Post' was ignored from 'Include' in the query since the fix-up will automatically populate it. If any further navigations are specified in 'Include' afterwards then they will be ignored. Walking back include tree is not allowed. This exception can be suppressed or logged by passing event ID 'CoreEventId.NavigationBaseIncludeIgnored' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.When using
.ThenInclude().Where().ToListAsync()
:
InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Query.NavigationBaseIncludeIgnored': The navigation 'PostTagModel.Post' was ignored from 'Include' in the query since the fix-up will automatically populate it. If any further navigations are specified in 'Include' afterwards then they will be ignored. Walking back include tree is not allowed. This exception can be suppressed or logged by passing event ID 'CoreEventId.NavigationBaseIncludeIgnored' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
On mobile, but I can teach you how to use try catch blocks tomorrow when I'm around my PC if nobody else does before then.
To get you going, get rid of your theninclude(), but keep your first .include(), .where() and .tolistasync() pieces. See how that does.
I will say, typically you would actually map the results of the EF query to a DTO and use them, instead of returning the tracked items to your view. But that's another topic.
Thank you
I made an edit to that, stating to keep your first .include. Get rid of the .theninclude portion