What is the use/advantage of using CommandBehavior.CloseConnection in ExecuteReader()

后端 未结 6 1962
甜味超标
甜味超标 2020-12-14 09:38

Can anyone tell me what is the CommandBehavior.CloseConnection and what is the use/benefit of passing this as a parameter in com.ExecuteReader(CommandBeha

6条回答
  •  抹茶落季
    2020-12-14 10:01

    I've found the best use of CommandBehavior.CloseConnection is when you want to write code that is flexible enough to be used in a transaction (which implies a shared connection for all queries). Consider:

    public DbDataReader GetReader(DbCommand cmd, bool close = true)
    {
        if(close)
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return cmd.ExecuteReader();
    }
    

    If you are running a read operation as part of a bigger transaction, you would want to pass false to this method. In either case, you should still use a using statement to do the actual read.

    Not in a transaction:

    using(var reader = GetReader(cmd, true))
    {
        while(reader.Read())
            ...
    }
    

    In a transaction, maybe checking for the existence of a record:

    bool exists = false;
    using(var reader = GetReader(cmd, false))
    {
        if(reader.Read())
            exists = reader.GetBoolean(0);
    }
    

    The first example will close the reader AND the connection. The second one (transactional) will still close the reader, but not the connection.

提交回复
热议问题