C
C#3w 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
}
}
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
Unable to cast object of type 'System.DBNull' to type 'System.String`
I got the above error in my app. Here is the original code public string GetCustomerNumber(Guid id) { string accountNumber = (string)DBSqlHelperFactory.ExecuteScalar(
1 Reply
taner.
taner.3w ago
U give the generic parameter a type 'string' but it expects the type 'ListingProjectsDTO' as generic So when you call the method, the value 'obj' is of type 'ListingProjectsDTO', but 'T' is a string. You're trying to convert 'ListingProjectsDTO' to a string, which you can't do

Did you find this page helpful?