我在Web项目和类库中运行以下代码,在NserviceBus主机上托管。
public static TravellerChannelModel GetTravellerInfo(Guid travellerId)
{
using (var conn = new SqlConnection(_travellerConnectionString))
{
var repo = new TravellerChannelRepository(_log, conn);
var travellerModel = repo.FindAll(travellerId).FirstOrDefault();
return travellerModel;
}
}
在网络项目中,它运行正常。在类库中我得到一个异常
ServiceBus.Unicast.Transport.TransportReceiver无法处理邮件 System.InvalidOperationException:ExecuteReader需要打开和 可用连接。连接的当前状态已关闭。 在System.Data.SqlClient.SqlCommand.ValidateCommand(String方法,布尔值 异步)...
如果我添加
conn.Open();
使用"之后,它就可以了。谁知道原因?
更新
这是TravellerChannelRepository。没有使用SqlDataAdapter。
我知道在查询和修改数据之前我必须打开连接。在这种情况下,我很好奇是什么打开了连接而不是我明确地做了。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using DapperExtensions;
using log4net;
namespace Traveller
{
public class TravellerChannelRepository
{
private readonly ILog _log;
private readonly IDbConnection _connection;
public TravellerChannelRepository(ILog log, IDbConnection connection)
{
_log = log;
_connection = connection;
}
public IEnumerable<TravellerChannelModel> FindAll(Guid travellerId)
{
IFieldPredicate predicate = Predicates.Field<TravellerChannelModel>(x => x.TravellerId, Operator.Eq, travellerId);
return _connection.GetList<TravellerChannelModel>(predicate);
}
}
}
答案 0 :(得分:0)
在查询或更新数据之前,始终必须打开SqlConnection。从头顶开始,不需要这个,就是SqlDataAdapter,因为它会自动为你打开连接。
示例中的某些代码隐藏在以下行之后:
var repo = new TravellerChannelRepository(_log, conn);
也许你在那里打开连接?
无论如何,在使用之前打开连接是完全正常的。