Ciao a tutti, ho un problema con nhibernate da diverso tempo e non sono
mai riuscito a risolvere, provo a descrivere in modo chiaro il problema.
Vorrei
salvare e modificare una lista di oggetti collegati tramite FK
all'oggetto padre in cascata utilizzando le funzionalità di NHibernate.
Non riesco a capire dove sbaglio, chi può aiutarmi?
Le tabelle sul DB sono:

Mapping Evento:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="Data.Model" namespace="Data.Model.Domain.Eventi" xmlns="urn:nhibernate-mapping-2.2">
<class name="Eventi" table="Eventi" lazy="true" schema="Evento">
<id name="CodiceEvento" column="CodiceEvento" />
<many-to-one name="TipiEvento" update="false" insert="false">
<column name="CodiceTipoEvento" sql-type="smallint" not-null="true" />
</many-to-one>
<property name="CodiceTipoEvento" >
<column name="CodiceTipoEvento" sql-type="smallint" not-null="true" />
</property>
<many-to-one name="TipiAltroEvento" update="false" insert="false">
<column name="CodiceTipoAltroEvento" sql-type="smallint" not-null="false" />
</many-to-one>
<property name="CodiceTipoAltroEvento" >
<column name="CodiceTipoAltroEvento" sql-type="smallint" not-null="false" />
</property>
<many-to-one name="TipiClasseEvento" update="false" insert="false">
<column name="CodiceTipoClasseEvento" sql-type="tinyint" not-null="true" />
</many-to-one>
<property name="CodiceTipoClasseEvento">
<column name="CodiceTipoClasseEvento" sql-type="tinyint" not-null="true" />
</property>
<many-to-one name="TipiCausaEvento" update="false" insert="false">
<column name="CodiceTipoCausaEvento" sql-type="tinyint" />
</many-to-one>
<property name="CodiceTipoCausaEvento" >
<column name="CodiceTipoCausaEvento" sql-type="tinyint" />
</property>
<many-to-one name="TipiStatoSchedaEvento" update="false" insert="false">
<column name="CodiceTipoStatoSchedaEvento" sql-type="tinyint" not-null="true" />
</many-to-one>
<property name="CodiceTipoStatoSchedaEvento">
<column name="CodiceTipoStatoSchedaEvento" sql-type="tinyint" not-null="true" />
</property>
<many-to-one name="GestoriAsset" update="false" insert="false">
<column name="CodiceGestoreAsset" sql-type="int" not-null="false" />
</many-to-one>
<property name="CodiceGestoreAsset">
<column name="CodiceGestoreAsset" sql-type="int" not-null="false" />
</property>
<many-to-one name="TipiOraEvento" update="false" insert="false">
<column name="CodiceTipoOraEvento" sql-type="tinyint" not-null="false" />
</many-to-one>
<property name="CodiceTipoOraEvento">
<column name="CodiceTipoOraEvento" sql-type="tinyint" not-null="false" />
</property>
<many-to-one name="TipiAutoreEvento" update="false" insert="false">
<column name="CodiceTipoAutoreEvento" sql-type="smallint" not-null="false" />
</many-to-one>
<property name="CodiceTipoAutoreEvento">
<column name="CodiceTipoAutoreEvento" sql-type="smallint" not-null="false" />
</property>
<many-to-one name="TipiSegnalazioneEvento" update="false" insert="false">
<column name="CodiceTipoSegnalazioneEvento" sql-type="smallint" not-null="false" />
</many-to-one>
<property name="CodiceTipoSegnalazioneEvento">
<column name="CodiceTipoSegnalazioneEvento" sql-type="smallint" not-null="false" />
</property>
<property name="DescrizioneEvento">
<column name="DescrizioneEvento" sql-type="varchar" not-null="false" />
</property>
<bag name="EventiDettaglio" table="EventiDettaglioBeneInteressato" schema="Evento" inverse="true" cascade="all,delete-orphan" >
<key column="CodiceEvento" />
<one-to-many class="EventiDettaglioBeneInteressato" />
</bag>
</class>
</hibernate-mapping>
Oggetto di dominio:
using System;
using System.Text;
using System.Collections.Generic;
using ERAsm.Data.Model.Attributes;
namespace Data.Model.Domain.Eventi
{
[Serializable, Observable]
public class Eventi : Entity, IEntity
{
public Eventi()
{
EventiDettaglio = new List<EventiDettaglioBeneInteressato>();
}
public virtual string CodiceEvento { get; set; }
public virtual string DescrizioneEvento { get; set; }
public virtual TipiEvento TipiEvento { get; set; }
public virtual TipiAltroEvento TipiAltroEvento { get; set; }
public virtual TipiClasseEvento TipiClasseEvento { get; set; }
public virtual TipiCausaEvento TipiCausaEvento { get; set; }
public virtual TipiStatoSchedaEvento TipiStatoSchedaEvento { get; set; }
public virtual GestoriAsset GestoriAsset { get; set; }
public virtual TipiOraEvento TipiOraEvento { get; set; }
public virtual TipiAutoreEvento TipiAutoreEvento { get; set; }
public virtual TipiSegnalazioneEvento TipiSegnalazioneEvento { get; set; }
public virtual short CodiceTipoEvento { get; set; }
public virtual short? CodiceTipoAltroEvento { get; set; }
public virtual byte CodiceTipoClasseEvento { get; set; }
public virtual byte? CodiceTipoCausaEvento { get; set; }
public virtual byte CodiceTipoStatoSchedaEvento { get; set; }
public virtual int? CodiceGestoreAsset { get; set; }
public virtual byte? CodiceTipoOraEvento { get; set; }
public virtual short? CodiceTipoAutoreEvento { get; set; }
public virtual short? CodiceTipoSegnalazioneEvento { get; set; }
public virtual IList<EventiDettaglioBeneInteressato> EventiDettaglio { get; set; }
#region NHibernate Composite Key Requirements
public override bool Equals(object obj)
{
if (obj == null) return false;
var t = obj as Eventi;
if (t == null) return false;
if (CodiceEvento == t.CodiceEvento)
return true;
return false;
}
public override int GetHashCode()
{
int hash = GetType().GetHashCode();
hash = (hash * 397) ^ CodiceEvento.GetHashCode();
return hash;
}
#endregion
}
}
Mapping EventiDettaglioBeneInteressato:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="Data.Model" namespace="Data.Model.Domain.Eventi" xmlns="urn:nhibernate-mapping-2.2">
<class name="EventiDettaglioBeneInteressato" table="EventiDettaglioBeneInteressato" schema="Evento" lazy="true" >
<composite-id>
<key-property name="PrgOrdinamento" column="PrgOrdinamento" />
<key-many-to-one class="Data.Model.Domain.Eventi.Eventi, Data.Model" name="Evento">
<column name="CodiceEvento" />
</key-many-to-one>
</composite-id>
<property name="DescrizioneAltroBeneRFI">
<column name="DescrizioneAltroBeneRFI" sql-type="varchar" not-null="false" />
</property>
<property name="NumQuantita">
<column name="NumQuantita" sql-type="bigint" not-null="false" />
</property>
<many-to-one name="TipiBeneRFI" update="false" insert="false">
<column name="CodiceTipoBeneRFI" sql-type="smallint" not-null="true" />
</many-to-one>
<property name="CodiceTipoBeneRFI">
<column name="CodiceTipoBeneRFI" sql-type="smallint" not-null="true" />
</property>
<many-to-one name="TipiRame" update="false" insert="false">
<column name="CodiceTipoRame" sql-type="varchar" not-null="false" />
</many-to-one>
<property name="CodiceTipoRame">
<column name="CodiceTipoRame" sql-type="varchar" not-null="false" />
</property>
<many-to-one name="TipiUnitaMisura" update="false" insert="false">
<column name="CodiceTipoUnitaMisura" sql-type="tinyint" not-null="false" />
</many-to-one>
<property name="CodiceTipoUnitaMisura">
<column name="CodiceTipoUnitaMisura" sql-type="tinyint" not-null="false" />
</property>
</class>
</hibernate-mapping>
Oggetto di dominio:
using System;
using System.Text;
using System.Collections.Generic;
using NHibernate.Proxy;
namespace Data.Model.Domain.Eventi
{
[Serializable]
public class EventiDettaglioBeneInteressato : Entity, IEntity
{
public virtual Eventi Evento { get; set; }
public virtual byte PrgOrdinamento { get; set; }
public virtual TipiBeneRFI TipiBeneRFI { get; set; }
public virtual TipiRame TipiRame { get; set; }
public virtual TipiUnitaMisura TipiUnitaMisura { get; set; }
public virtual short CodiceTipoBeneRFI { get; set; }
public virtual string CodiceTipoRame { get; set; }
public virtual byte? CodiceTipoUnitaMisura { get; set; }
public virtual string DescrizioneAltroBeneRFI { get; set; }
public virtual long? NumQuantita { get; set; }
#region NHibernate Composite Key Requirements
public override int GetHashCode()
{
unchecked
{
int hash = GetType().GetHashCode();
hash = (hash * 397) ^ PrgOrdinamento.GetHashCode();
hash = (hash * 397) ^ (Evento == null ? 0.GetHashCode() : Evento.GetHashCode());
return hash;
}
}
public override bool Equals(object obj)
{
return Equals(obj as EventiDettaglioBeneInteressato);
}
public virtual bool Equals(EventiDettaglioBeneInteressato other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(other, this))
{
return true;
}
var otherType = NHibernateProxyHelper.GetClassWithoutInitializingProxy(other);
var thisType = NHibernateProxyHelper.GetClassWithoutInitializingProxy(this);
if (!otherType.Equals(thisType))
{
return false;
}
bool otherIsTransient = Equals(other.Evento, null) && Equals(other.PrgOrdinamento, 0);
bool thisIsTransient = Equals(Evento, null) && Equals(PrgOrdinamento, 0);
if (otherIsTransient || thisIsTransient)
return false;
return Equals(other, this);
}
private bool Equals(EventiDettaglioBeneInteressato a, EventiDettaglioBeneInteressato b)
{
if (a.Evento == b.Evento
&& a.PrgOrdinamento == b.PrgOrdinamento)
return true;
return false;
}
#endregion
}
}
Test:
[TestMethod]
public void EventoTest_Add_Child_BeniInteressati()
{
var codiceEvento = "20140630_013325_BA";
using (var session = IoC.Container.Resolve<ISessionFactory>().OpenSession())
{
var evento = session.Get<Data.Model.Domain.Eventi.Eventi>(codiceEvento);
Assert.AreEqual(evento.EventiDettaglio.Count, 0);
var beneInteressato = new Data.Model.Domain.Eventi.EventiDettaglioBeneInteressato();
beneInteressato.PrgOrdinamento = 1;
beneInteressato.Evento = evento;
beneInteressato.CodiceTipoBeneRFI = 1;
evento.EventiDettaglio.Add(beneInteressato);
var beneInteressato2 = new Data.Model.Domain.Eventi.EventiDettaglioBeneInteressato();
beneInteressato.PrgOrdinamento = 2;
beneInteressato.Evento = evento;
beneInteressato.CodiceTipoBeneRFI = 2;
evento.EventiDettaglio.Add(beneInteressato2);
session.SaveOrUpdate(evento);
session.Flush();
}
}
Errore:
Message:
Cannot insert the value NULL into column 'CodiceEvento', table 'Evento.EventiDettaglioBeneInteressato'; column does not allow nulls. INSERT fails.
The statement has been terminated.
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.SqlClient.SqlCommand.ExecuteBatchRPCCommand()
at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientSqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
LOG:
18:15:25.695 [10] WARN NHibernate.Engine.ForeignKeys - Unable to determine if Data.Model.Domain.Eventi.EventiDettaglioBeneInteressato with assigned identifier Data.Model.Domain.Eventi.EventiDettaglioBeneInteressato is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.
18:15:25.716 [10] WARN NHibernate.Engine.ForeignKeys - Unable to determine if Data.Model.Domain.Eventi.EventiDettaglioBeneInteressato with assigned identifier Data.Model.Domain.Eventi.EventiDettaglioBeneInteressato is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.
18:15:25.960 [10] WARN NHibernate.Util.ADOExceptionReporter - System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'CodiceEvento', table 'Evento.EventiDettaglioBeneInteressato'; column does not allow nulls. INSERT fails.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.SqlClient.SqlCommand.ExecuteBatchRPCCommand()
at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientSqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
ClientConnectionId:b0edabca-f2b9-4cc5-95b8-120653b5dc31
18:15:26.012 [10] ERROR NHibernate.Util.ADOExceptionReporter - Cannot insert the value NULL into column 'CodiceEvento', table 'Evento.EventiDettaglioBeneInteressato'; column does not allow nulls. INSERT fails.
The statement has been terminated.
18:15:26.047 [10] ERROR NHibernate.Event.Default.AbstractFlushingEventListener - Could not synchronize database state with session
NHibernate.Exceptions.GenericADOException: could not execute batch command.[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'CodiceEvento', table 'Evento.EventiDettaglioBeneInteressato'; column does not allow nulls. INSERT fails.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.SqlClient.SqlCommand.ExecuteBatchRPCCommand()
at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientSqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
--- End of inner exception stack trace ---
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
at NHibernate.AdoNet.AbstractBatcher.ExecuteBatchWithTiming(IDbCommand ps)
at NHibernate.AdoNet.AbstractBatcher.ExecuteBatch()
at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
at NHibernate.Engine.ActionQueue.ExecuteActions()
at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
Grazie 1000.
Salvatore