I have the following method in the Helper
class which I am using it with Dapper:
Helper.cs:
public SqlMapper.GridReader MQueries(string spName, object dynamicParams)
{
using (IDbConnection conn = new SqlConnection(ConfigurationManager.AppSettings["MyConnection"]))
{
conn.Open();
return conn.QueryMultiple(spName, dynamicParams, commandType: CommandType.StoredProcedure);
}
}
And I call the above method from another class called DataAccess
:
DataAccess.cs:
public Member GetMemberDetails(Member member)
{
var multi = Helper.MQueries("GetMemberDetails", member);
var member = multi.Read<Member>().Single();
var memberStatus = multi.Read<MemberStatus>().Single();
var memberContact = multi.Read<MemberContact>().ToList();
var memberFinancial = multi.Read<MemberFinancial>().ToList();
member.MemberStatus = memberStatus;
member.MemberContact = memberContact;
member.MemberFinancial = memberFinancial;
return member;
}
However, the multi variable
have the data, but once I want to separate it and map into another variable, I got the exception called cannot read while the reader is closed
.
I know that is because I am used the using statement
, so after the multi variable
, the connection get closed automatically, therefore I cant read anything..
How can I solve this?
Your answer much appreciated
Thanks
The connection is getting closed before you attempt to read it. That won't work.
I would suggest to try like this:
using (var connection = new SqlConnection(ConfigurationManager.AppSettings["MyConnection"]))
using (var result = connection.QueryMultiple("GetMemberDetails", commandType: CommandType.StoredProcedure))
{
//... Consume
}