Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I work in visual studio 2015 mvc 5 entityframework 6 code first from existing database

I need to insert data based on existing stored procedure but i dont know How to do that

what is wrong in code below

SQL
step 1

USE [EmployeeSystem]
GO
/****** Object: StoredProcedure [dbo].[spAddDepartment] Script Date: 13/02/2018 12:32:38 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[spAddDepartment]
@DepartmentName nvarchar(50)
as 
Begin 
Insert into Departments values(@DepartmentName,1) 
End


C#
step2

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>().MapToStoredProcedures
(
s => s.Insert(i => i.HasName("spAddDepartment"))
);
base.OnModelCreating(modelBuilder);

}


step3

C#
public ActionResult Insert(Department depart)
{
// return View();
hr.Departments.Add(depart);
hr.SaveChanges();
return View(depart);
}


What I have tried:

How to insert data using existing stored procure mvc
Posted
Updated 12-Feb-18 12:17pm
Comments
Richard Deeming 13-Feb-18 10:26am    
What error are you getting?

Have you compared your code to the documentation[^]?

1 solution

There is SqlQuery method available in entity Framework to call the stored procedures or execute sql statements.

Please have a look at following:
https://stackoverflow.com/q/20901419
 
Share this answer
 
Comments
ahmed_sa 12-Feb-18 18:19pm    
OK but this way above when i use it
onmodelcreating
Ehsan Sajjad 13-Feb-18 9:21am    
You need to call it where you want to actually invoke the stored procedure, currently in your controller action

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900