Good evening! I use Entity Framework Code First.
Created a stored procedure through SQL Server Object Explorer.
How do I call it now through the context?

Earlier, when using DB First, the stored procedure could be called through the context as a normal method. How to achieve this using Code first?

    1 answer 1

    Working with stored procedures in the Code First approach needs to be organized manually. To do this, use the SqlQuery methods - to execute a query that returns data, - or ExecuteSqlCommand - to execute a command.

    For example, to call the GetPeople stored procedure with the Age parameter, which returns a list of people of a certain age, you need to create a model class that will accept data (or use an existing class if it fits):

     public class PersonInfo { public int Id { get; set; } public string Name { get; set; } // другие необходимые свойства } 

    Now you can call the store as follows:

     string sql = @"GetPeople {0}"; var people = context.Database.SqlQuery<PersonInfo>(sql, 42); foreach (var personInfo in people) { ... } 

    Of course, for convenient use, you can define a method in a context class:

     public class Context : DbContext { public DbRawSqlQuery<PersonInfo> GetPeople(int age) { var sql = @"GetPeople {0}"; return Database.SqlQuery<PersonInfo>(sql, age); } } 

    After that, you can call the stored procedure as follows:

     var people = context.GetPeople(42);