I am doing transition for a project from Webforms to MVC application using Entity Framework database first approach and have database ready along with all stored procedures
I implemented it through this well explained link to use stored procedures for CUD (create, update, delete) operations for an entity in the database-first approach.
Steps I followed (concept is still unclear for me, but it worked as per my requirement), but I hope it may help someone else as well:
Added ADO Entity Data Model using Database First Approach.
Added a new Controller for my entity using "MVC5 Controller with Views using EF" option.
For the DeleteConfirmed() function, i made minor changes as below:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int eid,bool isdeletede)
{
emp emp1 = db.emp.Find(eid,isdeletede); //Composite Key in my Entity: Emp
// db.emp.Remove(emp_sd1);
db.sp_deleteempt1(eid); //I excluded Remove() and invoked my Stored Procedure & it worked well for me
db.SaveChanges();
return RedirectToAction("grpindex");
}
public class EmployeeProcedure
{
[Column("EmpId")]
public int EmployeeId { get; set; }
[NotMapped]
public string FullName { get; set; }
public double Salary { get; set; }
}
after that call this:
this.Database.SqlQuery<EmployeeProcedure>("GetAllEmpDetails");
How to map a stored procedure in EF?
Since you are doing Database First Approach and you have an EDMX file, let EF generate the class of the stored procedure result for you. You may have many stored procedures and you want to avoid creating the classes manually: After all that is the whole point of using an ORM tool. Also some of your stored procedures may have parameters. Doing it the way below will handle all that for you. It is actually pretty simple.
To get EF to do this for you, follow the steps to below:
You will see the dialog similar to below:
That will add the stored procedure and you will see it in your model browser as shown below:
Some Notes
This is much better than writing the classes manually in case your stored procedure name, or the parameters it needs, or the result it returns changes. This approach will work for user defined functions as well.
A Gotcha
There will be times when the stored procedure will not appear in the selection in the wizard dialog, that is because of this. Simply add this to the beginning of your stored procedure:
SET FMTONLY OFF -- REMEMBER to remove it once the wizard is done.