I have MVC web application project with Entity Framework code first. In this project I am going to use generic repository and unit of work patterns. Plus I want to use stored procedures for get list by and get-list
methods.
How can I use stored procedures with generic repository and unit of work patterns?
UoW and Repository pattern are better suited to using ADO.NET directly and not Entity Framework, as EF is already a Repository pattern. I would suggest CQRS as a better pattern when using SPs. Elaborating on the answer by @sunil and my comment on it, I created a class specifically for handling stored procedures. It's easy to mock and test, too.
Entity Framework has a DbSet class which has Add and Remove method and therefore looks like a repository. the DbContext class has the method SaveChanges and so looks like the unit of work. Therefore I thought that it is possible to use entity framework and have all the Advantages of the Repository and Unit of Work pattern out of the box.
You can use stored procedures either to get the data or to add/update/delete the records for one or multiple database tables. EF API creates a function instead of an entity in EDM for each stored procedure and User-Defined Function (UDF) in the target database. Let's use stored procedure to fetch the data from the database.
You shouldn't be trying to use SPs with UoW/Repository pattern, because they are hard to control in code and often don't map back to the same entity type. UoW and Repository pattern are better suited to using ADO.NET directly and not Entity Framework, as EF is already a Repository pattern. I would suggest CQRS as a better pattern when using SPs.
For Generic Repository Add this :
public IEnumerable<TEntity> GetdataFromSqlcommand(string command, System.Data.SqlClient.SqlParameter[] parameter)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append($"EXECUTE {command}");
strBuilder.Append(string.Join(",", parameter.ToList().Select(s => $" @{s.ParameterName}")));
return Context.Set<TEntity>().FromSql(strBuilder.ToString(), parameter);
}
And you just need to send Stored Procedure name and the array of parameters :
public IEnumerable<MainData> GetMainData(Param query)
{
var param1 = new SqlParameter("param1", query.param1);
var param2 = new SqlParameter("param2", query.param2);
return GetdataFromSqlcommand("StoredProcedurename", parameter: new[] { param1, param2 }).ToList();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With