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

asp.net-mvc-3 c# entity-framework stored-procedures

Question

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);
    }
}
1
6
10/3/2012 1:14:34 PM

Popular Answer

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.

6
10/3/2012 12:08:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow