Visual Studio - Stored procedures

by
Jeremy Canfield |
Updated: March 13 2020
| Visual Studio articles
For the purpose of this tutorial, let's say you have already created an Entity Framework Model, View, and Controller in MVC. Under the /View/Example/ folder, you have a file Stage.cshtml, which maps to www.example.com/Example/Stage. We want to use a stored procedure on the Stage page.
You should already have a file under Models that contains a public class for DbContext. In this example, the public class is My_db : DbContext.
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Web.Mvc;
namespace Example.Models
{
public class table_name
{
. . .
}
public class My_db : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
};
public DbSet<table_name> table_name{ get; set; }
}
}
Enable migrations.
- Select Tools > NuGet Package Manager > Package Manager Console.
- Type Enable-Migrations -ContextTypeName Example.Models.My_db and press enter. Replace Example.Models.My_db with the namespace and DbContext name in your file. This will add a folder named Migrations and a file named Configuration.cs.
This allows the public class My_db : DbContext to use stored procedures. We next need to tell public class My_db : DbContext to use our stored procedures.
- Add modelBuilder.Entity<table_name>().MapToStoredProcedures(); inside public class My_db : DbContext.
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Web.Mvc;
namespace Example.Models
{
public class table_name
{
. . .
}
public class Example : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<table_name>().MapToStoredProcedures
(
s => s.Query(q => q.HasName("[dbo].[table_name]"));
);
};
public DbSet<table_name> table_name{ get; set; }
}
}
- Press Ctrl + Shift + B to build the solution.
Add a migration:
- Select Tools > NuGet Package Manager > Package Manager Console.
- Type Add-Migration MyStoredProcedures and press enter. Replace MyStoredProcedures with a unique name of your choosing. This will add a folder named Migrations and a file named xxxxxxxxxxxx_MyStoredProcedures.cs.
Did you find this article helpful?
If so, consider buying me a coffee over at