The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid

c# entity-framework sql

Question

I'm using Entity Framework 6.0.2; before to this problem, I was using an earlier version.

Basically, this has always worked: I set my models' "string" properties, run a query or stored procedure, then output the results as strings.

Any suggestions for a fix? Maybe I could use a "Convention" for the conversion?

Ex:

SQL:
select ROW_NUMBER() OVER (ORDER BY (select Null)) AS Id, '0', 'Test0', 'some kind of data', 'Test1', 'possibly a datetime type', 'Test2'

C#:
public class SomeModel
{
    public int Id { get; set; }
    public string Test0 { get; set; }
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

Invalid Operation Exception:
var records = dbContext.Database.SqlQuery<SomeModel>("select ROW_NUMBER() OVER (ORDER BY (select Null)) AS Id, '0', 'Test0', 'some kind of data', 'Test1', 'possibly a datetime type', 'Test2'").ToList();    

.

1
3
1/23/2019 3:28:48 AM

Popular Answer

even though it has been unanswered for a year. Based on a statement made above by @Crono, I have my own response to offer.

Basically, datatypes were the problem. The datatypes from SQL to.NET must be translated by Entity Framework in order to tie a SQL result set to a model.

However, in.NET Since the purpose of the data being retrieved is to show it on a webpage or in a file, not to change it in any way, I wanted everything to come back as a string.

To convert all result columns to varchar, the query required to be changed. which @Crono graciously elucidated in his remark earlier. I couldn't use a view because the data and outcomes aren't known.

2016-07-2 zzzz-19 zzzz

Cast your principles!

select Cast(ROW_NUMBER() OVER (ORDER BY (select Null)) AS Id as int), Cast('0' as varchar(255)), Cast('Test0' as varchar(255)), Cast('some kind of data' as varchar(255)), Cast('Test1' as varchar(255)), Cast('possibly a datetime type' as varchar(255)), Cast('Test2' as varchar(255))
4
7/2/2016 7:07:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow