NHibernate extract DBTransaction from Session
I have an legacy db where some stored proc calculates the row ids for all the tables. Now I want to overwrite the IIdentifierGenerator as hinted at this page http://www.richter-web.info/Wordpress/?p=132 just to avoid the Id(x => x.id).GenereatedBy.Assigned.
Now as I save some object,of course inside an Nhibernate transaction, named AppendixHierarchy, then as soon as it gets into ATKIdGenerator.Generate and it starts command.ExecuteNonQuery() I receive some exception ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pendi开发者_运维技巧ng local transaction. The Transaction property of the command has not been initialized.
How can I extract the DB Transaction from the Nhibernate session object, in order to attach it to the command?
I used the FluentMapping for the poco
public AppendixHierarchyMap()
{
Table("appendixHierarchy");
Id(x => x.id).GeneratedBy.Custom(typeof(ATKIdGenerator), a => a.AddParam("TableName", "appendixHierarchy"));
.....
And here is the Id Generator
public class ATKIdGenerator : IIdentifierGenerator, IConfigurable
{
private string TableName { get; set; }
#region IIdentifierGenerator Members
public object Generate(NHibernate.Engine.ISessionImplementor session, object obj)
{
IDbCommand command = new SqlCommand();
command.Connection = session.Connection;
//transaction.Enlist(command);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.ups_GetNewId";
// Set input parameters
var parm = new SqlParameter("@tableName", SqlDbType.VarChar);
parm.Value = TableName;
command.Parameters.Add(parm);
// Set output parameter
var outputParameter = new SqlParameter("@id", SqlDbType.Int);
outputParameter.Direction = ParameterDirection.Output;
command.Parameters.Add(outputParameter);
// Set a return value
var returnParameter = new SqlParameter("@RETURN_VALUE", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnParameter);
// Execute the stored procedure
command.ExecuteNonQuery();
return (int)((SqlParameter)command.Parameters["@id"]).Value;
}
#endregion
#region IConfigurable Members
public void Configure(NHibernate.Type.IType type, IDictionary<string, string> parms, NHibernate.Dialect.Dialect d)
{
TableName = parms["TableName"];
}
#endregion
}
I think you need to open another connection in generate method rather then re-using one on the session.
精彩评论