Stored Procedures

Apr 30, 2012 at 12:21 PM

Hi,

I've been come to a stumbling block. I'm aware repository design give us an abstracted to access the database.

I have a few stored procedures in the database how do I go about accessing them through the repository, or would I need to resorting to access my ORM (EF) directly. I've tried searching the internet but there isn't much information around on this.

Thanks.

Coordinator
May 3, 2012 at 9:01 PM
Edited May 3, 2012 at 9:01 PM

Hello Madness2K4,

the solution is to use the SqlQuery<T> method accessible from your DbContext.Database object.

Here is an example of a custom Repository that use stored procedure :

 

using System.Collections.Generic;
using System.Data.Entity;
using EntityFramework.Patterns;

namespace efPatternsWorkbench
{
    public class ProcStockRepository : Repository<WorkBench>
    {
        private readonly DbContext _context;

        public ProcStockRepository(IObjectSetFactory objectSetFactory, DbContext context): base(objectSetFactory)
        {
            _context = context;
        }

        public  IEnumerable<WorkBench> LoadViaProcStock()
        {
            //IEnumerable<WorkBench> res = _context.Database.SqlQuery<WorkBench>("SELECT * FROM WorkBenches");
            IEnumerable<WorkBench> res = _context.Database.SqlQuery<WorkBench>("EXEC GetWorkbenches");

            return res;
        }

    }
}

I hope this helps.