Search code examples
stored-proceduresentity-framework-coreasp.net-core-2.0entity-framework-core-migrations

EF Core 2.0 how to use SQL stored procedure


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


Solution

  • You can use the FromSQL method:

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

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