I am using Entity Framework 4.1 and do sometimes need to call stored procedures. Some of these return ints as return values. For instance
CREATE PROCEDURE ...
...
INSERT INTO ...
SELECT @@Identity
(Update: removed return value, not relevant. We're returning the identity)
I have the following code in my respository class:
var orderNo = context.Database.SqlQuery<int>("EXEC myProc").Single();
This fails with the error message The specified cast from a materialized 'System.Decimal' type to the 'System.Int32' type is not valid.
If I change the code above to
var orderNo = context.Database.SqlQuery<decimal>("EXEC myProc").Single();
everything works.
Now, I think that I should be able to return an int. What's the proper way to do this?
I assume, based on the edit to your question - I clicked it shortly after your posting, then refreshed a bit later - that this is only an issue when you're returning the identity?
If so, it's a decimal because @@IDENTITY (and SCOPE_IDENTITY) return numeric(38,0). See the answer to this question: Why does select SCOPE_IDENTITY() return a decimal instead of an integer? As noted there, casting to int should allow the EF to properly detect the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With