0

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.

0

1 Answer 1

0

This may provide an answer to what you need.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Calling function in LINQ expression solved my problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.