Почему Nhibernate использует неправильное имя Id? - PullRequest
1 голос
/ 20 июля 2011

У меня проблема с тем, что мой беглый не использует указанные мной имена. Например, у меня есть ExtraEventSettingsId. Все же он ищет ExtraEventSettingId (он сбросил «s» из настроек).

Не знаю почему.

У меня есть это

свободный

   ISessionFactory fluentConfiguration = Fluently.Configure()
                                              .Database(MsSqlConfiguration.MsSql2008.ConnectionString("string"))
                                              .Mappings(m => m.FluentMappings.AddFromAssemblyOf<StudentMap>().Conventions.Add(ForeignKey.EndsWith("Id")))
                                              .ExposeConfiguration(cfg => cfg.SetProperty("adonet.batch_size", "20"))
                                              .ExposeConfiguration(c => c.SetProperty("generate_statistics", "true"))
                                              .BuildSessionFactory();

Отображение, которое, кажется, вызывает проблемы

  public class ExtraEventSettingsMap :  ClassMap<ExtraEventSetting>
    {
        public ExtraEventSettingsMap()
        {
            Table("ExtraEventSettings");
            Id(x => x.Id).Column("ExtraEventSettingsId");
            Map(x => x.BackgroundColor).NvarcharWithMaxSize().Not.Nullable();
            Map(x => x.Title).NvarcharWithMaxSize().Not.Nullable();
            HasMany(x => x.TimeTableEvents).Cascade.All();
            References(x => x.TimeTable).Not.Update().Not.Nullable();
        }
    }

Код, который я пытаюсь запустить (пытается взять объект и выполнить обновление с ним)

  public void Update(ExtraEventSetting extraEventSettings)
    {
            nhibernateRepo.Update(extraEventSettings);
            nhibernateRepo.Commit();
    }

Объект extraEventSettings имеет все, что изменилось, и имеет идентификатор (pk).

Вот что происходит, когда происходит ошибка. Invalid column name 'ExtraEventSettingId' ищет столбец ExtraEventSetting, когда он должен быть ExtraEventSettings.

NHibernate.Exceptions.GenericADOException was caught
  Message=could not delete collection: [ExtraEventSetting.TimeTableEvents#1][SQL: UPDATE TimeTableEvents SET ExtraEventSettingId = null WHERE ExtraEventSettingId = @p0]
  Source=NHibernate
  SqlString=UPDATE TimeTableEvents SET ExtraEventSettingId = null WHERE ExtraEventSettingId = @p0
  StackTrace:
       at NHibernate.Persister.Collection.AbstractCollectionPersister.Remove(Object id, ISessionImplementor session)
       at NHibernate.Action.CollectionRemoveAction.Execute()
       at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
       at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
       at NHibernate.Engine.ActionQueue.ExecuteActions()
       at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
       at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
       at NHibernate.Impl.SessionImpl.Flush()
       at NHibernate.Transaction.AdoTransaction.Commit()
       at NhibernateRepo.Commit() in line 24
       at Update(ExtraEventSetting extraEventSettings) in line 228
  InnerException: System.Data.SqlClient.SqlException
       Message=Invalid column name 'ExtraEventSettingId'.
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=16
       LineNumber=1
       Number=207
       Procedure=""
       Server=(local)
       State=1
       StackTrace:
            at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
            at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
            at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
            at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
            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)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
            at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
            at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
            at NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
            at NHibernate.Persister.Collection.AbstractCollectionPersister.Remove(Object id, ISessionImplementor session)
       InnerException: 

вот исходное отображение nhibernate

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class xmlns="urn:nhibernate-mapping-2.2" name="Framework
.Domain.ExtraEventSetting, Framework, Version=1.0.0.0, Cult
ure=neutral, PublicKeyToken=null" table="ExtraEventSettings">
    <id access="backfield" name="Id" type="System.Int32, mscorlib, Version=4.0.0
.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="ExtraEventSettingsId" />
      <generator class="identity" />
    </id>
    <bag cascade="all" name="TimeTableEvents">
      <key>
        <column name="ExtraEventSetting_id" />
      </key>
      <one-to-many class="Framework.Domain.TimeTableEvent,
Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken
=null" />
    </bag>
    <property name="BackgroundColor" type="System.String, mscorlib, Version=4.0.
0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="BackgroundColor" length="10000" not-null="true" />
    </property>
    <property name="Title" type="System.String, mscorlib, Version=4.0.0.0, Cultu
re=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Title" length="10000" not-null="true" />
    </property>
    <many-to-one class="Framework.Domain.TimeTable, OnlineS
tudentPlanner.Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
name="TimeTable" update="false">
      <column name="TimeTable_id" not-null="true" />
    </many-to-one>
  </class>
</hibernate-mapping>

ExtraEventSettings

 public class ExtraEventSetting
    {
        public virtual int Id { get; private set; }
        public virtual string BackgroundColor { get; set; }
        public virtual string Title { get; set; }
        public virtual IList<TimeTableEvent> TimeTableEvents { get; set; }
        public virtual TimeTable TimeTable { get; set; }

        public ExtraEventSetting()
        {
            TimeTableEvents = new List<TimeTableEvent>();
        }
    }
...