3

I am trying to get output value from the dbcontext using the method FromSql(...).

If i execute it on SSMS, it works but not working in EF core.

My SP param:

  @totalItems VARCHAR(MAX) OUTPUT 

I've removed other params for readable and point out the issue. The records are coming but the OUTPUT parameter is always null.

Linq

IQeryable<T> = _context.Set<T>().FromSql("Sp_Todo @totalItems OUTPUT", // i also tried with OUT or without both Out/Output but no luck
 new SqlParameter("@totalItems", SqlDbType.Varchar)
 { Direction = ParameterDirection.Output});
8
  • Your database is using VARCHAR while the c# query has BigInt. Commented Jul 27, 2017 at 6:50
  • Even if i put SqlDbType.VarChar returns null. Commented Jul 27, 2017 at 6:55
  • try "string query=" in place of "var query=" Commented Jul 27, 2017 at 7:19
  • 1
    Ashu The query isn't the string. It is IQeryable<T> You can see at _context.Set<T>() Commented Jul 27, 2017 at 7:57
  • Not an answer, but it should be IQueryable, not IQeryable. Also, you can use @ to mention people in comments. For example, @Robin. Commented Jul 27, 2017 at 8:23

1 Answer 1

2

I don't' have access to your whole code, but nothing ever gets executed against your queryable source until you try to enumerate it. So, probably it didn't run the Stored Procedure when you tried to get the OUTPUT.

To force immediate query evaluation you can do it:

 IQueryable<T> foo = _context.Set<T>().FromSql("Sp_Todo @totalItems OUTPUT", new SqlParameter("@totalItems", SqlDbType.Varchar) { Direction = ParameterDirection.Output });
 //totalItems output still null
 var bar = foo.ToList()
 //totalItems output not null anymore

Here's how I'm doing it:

var _companyCode = new SqlParameter("CompanyCode", "HST");
var _sMsg = new SqlParameter("sMsg", "")
{
    Direction = ParameterDirection.Output,
    SqlDbType = SqlDbType.VarChar
};

var sql = "exec temp_get_company @CompanyCode, @sMsg OUTPUT";

var result = context.Set<Company>().FromSql(sql, _companyCode, _sMsg).ToList();

var yourOutput = _sMsg.Value.ToString();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.