Many forum post I have read people asking question how to pass stored procedure Using Dapper.NET ORM in MVC. many answers were good but much complicated. So I have decided to make it very simple .Please read my previous article to understand the basics about MVC:
Suppose you have following Model class
- ActionResult in ASP.NET MVC.
- Creating an ASP.NET MVC Application.
- CRUD Operations In ASP.NET MVC 5 Using ADO.NET
- Convert DataTable To Generic List In ASP.NET MVC .
- Show Confirm Alert Box on ActionLink Click In ASP.NET MVC.
- Convert DataTable To Generic List Using LINQ In ASP.NET MVC.
- How to Change ActionLink Text Color In ASP.NET MVC .
- How to Call Another Controller View Using ActionLink In ASP.NET MVC .
- Convert DataTable To Generic List Using AsEnumerable In ASP.NET MVC .
Suppose you have following Model class
public class EmpModel { [Display(Name = "Id")] public int Empid { get; set; } [Required(ErrorMessage = "First name is required.")] public string Name { get; set; } [Required(ErrorMessage = "City is required.")] public string City { get; set; } [Required(ErrorMessage = "Address is required.")] public string Address { get; set; } }
Now consider following stored procedure we have
Create procedure [dbo].[AddNewEmpDetails] ( @Id int=null), @Name varchar (50), @City varchar (50), @Address varchar (50) ) as begin Insert into Employee values(@Name,@City,@Address) End
Now following is the function which is used to pass above stored procedure to Dapper.NET
public void AddEmployee(EmpModel objEmp) { //Passing stored procedure using Dapper.NET connection(); con.Execute("AddNewEmpDetails", objEmp, commandType: CommandType.StoredProcedure); }
In the above function
- Connection() is the method which contains the connection string .
- Con is the SqlConnection class object.
- AddNewEmpDetails is the stored procedure.
- ObjEmp is the object of model class
Notes
- The above function will throw too much parameters than stored procedure because it must have to pass all parameters which are in model class .
- To avoid parameter exception error you must set null to the stored procedure parameter which is not passing model class parameter to stored procedure.
- If you are using above technique you must have same parameters in stored procedure as in model class.
- If you can not be wants to pass any model class parameter to the stored procedure then set null that parameter which I have set null to the Id parameter in the above stored procedure .
- You can use same function ,if you are passing list , nothing need to change .
I hope this article is useful for all readers. If you have any suggestion then please contact me.
Post a Comment