简体   繁体   中英

Calling a stored procedure in Entity Framework 6 Repository Pattern

I am familiar with Entity Framework (6) on a slightly more than basic level. I built a system based on a pattern I got from a book. I effectively makes all db calls nicely generic. It did not however address calling stored procedures and I have some that I need. I'm exactly sure how to call them based on this pattern.

Here is how it is established for Fetches:

public class EFRepository<T> : IRepository<T> where T : class
{
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");

        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }
    protected DbSet<T> DbSet { get; set; }

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual IQueryable<T> GetTop50()
    {
        return DbSet.Take(50);
    }

    public virtual T GetById(int id)
    {
        return DbSet.Find(id);
    }
}

So, I guess the question is, how would I make the call, passing in the name of the stored procedure and the parameter(s)? Is the result still a DbSet ? The stored procedure IS established in EF.

public virtual ObjectResult<PropertiesContactIsInvolvedIn_Result> PropertiesContactIsInvolvedIn(Nullable<int> contactID)
{
    var contactIDParameter = contactID.HasValue ?
            new ObjectParameter("ContactID", contactID) :
            new ObjectParameter("ContactID", typeof(int));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<PropertiesContactIsInvolvedIn_Result>("PropertiesContactIsInvolvedIn", contactIDParameter);
}

Additionally, as I said, there is a repository approach involved, and the entities are expressed like this:

public IRepository<PropertiesContactIsInvolvedIn_Result> PropertiesContactIsInvolvedIn { get { return GetStandardRepo<PropertiesContactIsInvolvedIn_Result>(); } }

IRepository<PropertiesContactIsInvolvedIn_Result> PropertiesContactIsInvolvedIn { get; }

You should be able to see the stored procedure in the context

using (var context = new EFRepository())
{
var ids= context.PropertiesContactIsInvolvedIn(id);  


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM