InvalidCastException: Unable to cast object of type
The full exception reads
InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[WebApplication1.Models.ListingProjectsDTO]' to type 'System.String'.
InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[WebApplication1.Models.ListingProjectsDTO]' to type 'System.String'.
The exception points at this method
public async Task<IActionResult> TestDashboard1() { var datasource = _context.ListingDTO_DBTable.AsQueryable(); var query = datasource .Select(x => new ListingProjectsDTO() { Id = x.Id, ListingName = x.ListingName, }); ConvertFromDBVal<string>(query); var listings = await query.ToListAsync(); return View(listings); } public static T ConvertFromDBVal<T>(object obj) { if (obj == null || obj == DBNull.Value) { return default(T); } else { return (T)obj; //InvalidCastException } }
public async Task<IActionResult> TestDashboard1() { var datasource = _context.ListingDTO_DBTable.AsQueryable(); var query = datasource .Select(x => new ListingProjectsDTO() { Id = x.Id, ListingName = x.ListingName, }); ConvertFromDBVal<string>(query); var listings = await query.ToListAsync(); return View(listings); } public static T ConvertFromDBVal<T>(object obj) { if (obj == null || obj == DBNull.Value) { return default(T); } else { return (T)obj; //InvalidCastException } }
`
I am not good at casting at all, I have tried return (System.string) obj. I tried to create a list with System.string data type with the help of foreach in the TestDashboard1(). Those of course failed.
Could anyone kindly point me in the right direction?