EF Core 2.0 how to use SQL stored procedure

Mukil Deepthi picture Mukil Deepthi · Jan 11, 2018 · Viewed 20.9k times · Source

I am new to EF Core 2.0 with stored procedure.

Can anyone help how to use stored procedure in my EF Core 2.0 code-first approach?

With my previous project, I had an .edmx model file, and I was using the context as below:

public IEnumerable<UserResult> GetUserResults(Entities context)
{
    if (context == null) return new List<UserResult>();
    return context.spGetUsers().Where(u => u.IsDeleted == false);
}

and the context is:

public virtual ObjectResult<UserResult> spGetUsers()
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<UserResult>("spGetUsers");
}

Thanks

Answer

ErikEJ picture ErikEJ · Jan 11, 2018

You can use the FromSQL method:

var blogs = context.Blogs
    .FromSql("EXECUTE dbo.GetMostPopularBlogs")
    .ToList();

https://docs.microsoft.com/en-us/ef/core/querying/raw-sql