Dapper.NET - 读取器关闭时调用FieldCount的尝试无效

时间:2015-01-16 09:45:08

标签: c# dapper sqldatareader

我正在执行一个返回多组数据的SP。

我有一个基类用于通用dapper执行和实际实现。调用后续行时,抛出异常:

[var projects = result.Read<ProjectViewModel>().ToList();]



public abstract class DapperRepositoryBase
{
    protected readonly IConnectionFactory _connectionFactory;
    protected readonly string _connectionStringName;

    protected DapperRepositoryBase(IConnectionFactory connectionFactory, string connectionStringName)
    {
        _connectionFactory = connectionFactory;
        _connectionStringName = connectionStringName;
    }

    protected DbConnection OpenConnection()
    {
        var connection = _connectionFactory.Create(_connectionStringName);
        connection.Open();
        return connection;
    }

    protected T Fetch<T>(Func<DbConnection, T> func)
    {
        if (func == null)
        {
            throw new ArgumentNullException("func");
        }

        using (var connection = OpenConnection())
        {
            return func(connection);
        }
    }

    protected int Execute(Func<DbConnection, int> func)
    {
        if (func == null)
        {
            throw new ArgumentNullException("func");
        }

        using (var connection = OpenConnection())
        {
            return func(connection);
        }
    }

    protected int ExecuteTransaction(Func<DbConnection, IDbTransaction, int> func, IsolationLevel isolationLevel = IsolationLevel.Serializable)
    {
        if (func == null)
        {
            throw new ArgumentNullException("func");
        }

        using (var connection = OpenConnection())
        using (var transaction = connection.BeginTransaction(isolationLevel))
        {
            var value = func(connection, transaction);

            transaction.Commit();

            return value;
        }
    }
}

然后我调用方法的方式如下:

public AViewModel GetDataForAScreen()
    {
        var viewmodel = new AViewModel();
        var result = Fetch(c => c.QueryMultiple("[dbo].[sp_GetAData]", param: null, commandType: CommandType.StoredProcedure));

        // get projects
        var projects = result.Read<ProjectViewModel>().ToList();
        viewmodel.Projects.AddRange(projects);

        // get signatures
        var signatures = result.Read<SignatureViewModel>().ToList();
        viewmodel.Signatures.AddRange(signatures);

        return viewmodel;
    }

0 个答案:

没有答案