存储过程的存储库模式

jod*_*dev 5 c# stored-procedures dependency-injection repository-pattern

我对存储库模式和依赖注入很新.我遇到的几乎所有存储库模式都有某种GetAll()方法,如下所示:

public interface IRepository<T>
{
    IQueryable<T> GetAll();
    // other CRUD methods here...
}
Run Code Online (Sandbox Code Playgroud)

我在实现此接口和GetAll()方法时遇到问题,因为我正在调用一个存储过程,该存储过程需要一个基于用户输入而更改的参数.我不想在存储库接口中添加ad-hoc方法,例如IQueryable<T> GetAll(string input);.我也不想在构造函数中添加一个参数,因为它对我来说有点乱:

public class ConcreteRepository : IRepository<Entity>
{
    string _storedProcedureInput;

    public ConcreteRepository(string storedProcedureInput)
    {
        _storedProcedureInput = storedProcedureInput;

    public IQueryable<Entity> GetAll()
    {
        // Call to stored procedure goes here passing in the 
        // _storedProcedureInput variable.
    }
}
Run Code Online (Sandbox Code Playgroud)

我也使用依赖注入,所以我必须在绑定时向构造函数添加一些动态输入:

Bind<IRepository<Entity>>().To<ConcreteRepository>().WithConstructorArgument(?)
Run Code Online (Sandbox Code Playgroud)

有什么建议?

更新:

我想重用IRepository接口.例如,在一个程序中,我使用EF4实现GetAll()方法,而在另一个程序中,我使用标准ADO.NET来调用存储过程,如上例所示.

Mar*_*tts 5

这听起来像你的GetAll不一定全部.在这种情况下,您也可以重命名它或使用另一种方法更准确地描述存储过程提供的功能,该功能采用可传递给过程的相应输入参数.


小智 5

你不能在你的IRepository中添加一个新方法来执行自定义存储过程:

    /// <summary>
    /// Execute Stored Proc with result set returned.
    /// </summary>
    /// <param name="procName"></param>
    /// <returns>An object resultset</returns>
    T ExecuteCustomStoredProc<T>(string procName, SqlParameter params);
Run Code Online (Sandbox Code Playgroud)

在您的实现(ConcreteRepository)中,您可以将此逻辑放入其中:

        public T ExecuteCustomStoredProc<T>(string commandName, SqlParameter params)
        {
            return this._repositoryContext.ObjectContext.ExecuteStoreQuery<T>(commandName, params);
        }
Run Code Online (Sandbox Code Playgroud)