Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a stored procedure using DBContext in ASP.NET MVC 3 Entity Framework

I do mapping here for tables.. How to map stored procedures here?

public class AppDBContext : DbContext
{
    public DbSet<UserAccount> UserAccount { get; set; }
    public DbSet<GetUserAccounts> GetGetUserAccounts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserAccount>().ToTable("UserAccount");
        modelBuilder.Entity<Customer>().ToTable("Customer");

        base.OnModelCreating(modelBuilder);
    }
}
like image 654
user1716929 Avatar asked Oct 03 '12 11:10

user1716929


People also ask

How can we call stored procedure in Entity Framework database first MVC?

Open the SchoolModel. Store node and then open the Stored Procedures node. Then right-click the GetCourses stored procedure and select Add Function Import. In the Add Function Import dialog box, under Returns a Collection Of select Entities, and then select Course as the entity type returned.

Can we use Entity Framework with stored procedure?

You can use stored procedures either to get the data or to add/update/delete the records for one or multiple database tables. EF API creates a function instead of an entity in EDM for each stored procedure and User-Defined Function (UDF) in the target database.


1 Answers

Code first does not support stored procedures.

You can execute scripts in a database initialiser using:

string sql = "CREATE PROCEDURE [MyProc]...";
context.Database.ExecuteSqlCommand(sql);

You can execute procedures them from the context like so:

string command = "EXEC MyProc";
IEnumerable<T> results = context.Database.SqlQuery<T>(command, null);

Personally, I wrap this up into a nice OO model. I have specialised SP class with strongly typed methods. These methods are decorated with an attribute that tells the DB initialiser to create a stored procedure of a given name from a given source. The strong type methods call the stored procedure.

like image 77
Paul Fleming Avatar answered Oct 10 '22 17:10

Paul Fleming