C#C
C#11mo ago
morry329#

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'.

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
        }
    }
`

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?

PS: if anyone is wondering why I am using the generic method here, see https://stackoverflow.com/questions/870697/unable-to-cast-object-of-type-system-dbnull-to-type-system-string
Stack Overflow
I got the above error in my app. Here is the original code

public string GetCustomerNumber(Guid id)
{
string accountNumber =
(string)DBSqlHelperFactory.ExecuteScalar(
Was this page helpful?