I have an interesting problem with EF Code First and MSSQL user defined functions. I write a database function that returns a scalar value and I want to map that function to my DbContext.
Based on information that I found I wrote this:
[DbFunction("AppDbContext", "GetNextDocumentNumber")]
public virtual int GetNextDocumentNumber()
{
return ((IObjectContextAdapter)this)
.ObjectContext
.ExecuteStoreCommand("GetNextDocumentNumber");
}
I also write a simple unit test to check if function returns correct values. The problem is that this code above returns -1. When I execute function on SMSS I get correct result.
After searching on the different sites I have found a solution thatlooks like this:
public virtual int GetNextDocumentNumber()
{
return this.Database
.SqlQuery<int>("select dbo.GetNextDocumentNumber()")
.Single();
}
In this case i get the correct value.
I just want to know what is wrong with the previous code or what am I doing wrong. In both cases I get a value. But only in one case value is correct.