我想让一个父对象在一个transactioncope中删除它自己和它的子对象。我还想检查两种情况是否存在要删除的对象,以及用户是否拥有该对象的权限。请考虑以下代码:
我得到服务器上的MSDTC不可用异常。无论如何通过我的服务方法传递连接?
请参阅以下示例:
//类Flight,FlightService,FlightDao //课程Pilot,PilotService,PilotDao
// FlightService
public void deleteFlight(Flight flight) {
FlightDao flightDao = new FlightDao();
Flight existingFlight = flightDao.findById(flight.Id);
if (existingFlight != null) {
using (TransactionScope scope = new TransactionScope()) {
try {
PilotService.Instance.deletePilot(flight.Pilot);
flightDao.delete(flight);
} catch (Exception e) {
log.Error(e.Message, e);
throw new ServiceException(e.Message, e);
}
scope.Complete();
}
}
}
// PilotService
public void deleteFlight(Pilot pilot) {
PilotDao pilotDao = new PilotDao();
Pilot existingPilot = pilotDao.findById(pilot.Id); // THIS LINE RIGHT HERE THROWS EXCEPTION
if (existingPilot != null) {
using (TransactionScope scope = new TransactionScope()) {
try {
pilotDao.delete(pilot);
} catch (Exception e) {
log.Error(e.Message, e);
throw new ServiceException(e.Message, e);
}
scope.Complete();
}
}
}
答案 0 :(得分:0)
您正在使用多个数据上下文层与事务。你需要将一个传递给另一个。 “ deletePilot ”调用应在相同的数据上下文中执行。一种解决方案是在数据访问层使用构造函数来接受来自其他数据服务的数据上下文。他们将在相同的环境中执行操作。
public void deleteFlight(IYourDataContext context, Pilot pilot) {
PilotDao pilotDao = new PilotDao(context);
//do operations now in same context.
...
答案 1 :(得分:0)
这里的问题是我试图在同一个循环中多次使用相同的SqlDataReader。这种行为在交易中不起作用。
示例:
SqlCommand command = new SqlCommand(...);
SqlDataReader reader = command.ExecuteReader();
if (reader.read()) {
return buildMyObject(reader);
}
private MyObject buildMyObject(SqlDataReader reader) {
MyObject o1 = new MyObject();
// set fields on my object from reader
// broken! i was attempting create a new sql connection here and attempt to use a reader
// but the reader is already in use.
return o1;
}