开发者

Incorrect component when querying immediately after insert using NHibernate

开发者 https://www.devze.com 2022-12-25 11:29 出处:网络
I have the following mapping for my table in MySql: <class name=\"Tag, namespace\" table=\"tags\" >

I have the following mapping for my table in MySql:

<class name="Tag, namespace" table="tags" >
 <id name="id" type="Int32" unsaved-value="0">
   <generator class="native"></generator>
 </id>
 <property name="name" type="String" not-null="true"></property>
 <component name="record_dates" class="DateMetaData, 开发者_运维问答namespace" >
   <property name="created_at" type="DateTime" not-null="true"></property>
   <property name="updated_at" type="DateTime" not-null="true"></property>
 </component>
</class>

As you see the record_dates property is defined as a component field of type DateMetaDate. Both created_at and updated_at fields in 'tags' table are updated via triggers. Thus I can insert a new record like such:

var newTag = new Tag() 
{ 
 name = "some string here"
}

Int32 id = (Int32)Session.Save(tag);
Session.Flush();

ITag t = Session.Get<Tag>(id);
ViewData["xxx"] = t.name; // -----> not null
ViewData["xxx"] = t.record_dates.created_at; // -----> is null

However when querying the same record back immediately after it was inserted the record_dates field ends up null even though in the table those fields have got values.

Can any one please point out why the Session.Get ignores getting everything back from the table? is it because it caches the newly created record for which the records_dates is null? If so how can it be told to ignore the cached version?


Try using lazy="false" in your class tag:

<class name="Tag, namespace" table="tags" lazy="false">

As per my knowledge, the default behavior is to have lazy loading, which might not refresh your objects as needed.


The only I so far have found is to call Session.Clear() method on the NHibernate session object, which I guess forces NHibernate to fetch the record from the table again. But I'm afraid it removes everything in cache and thus be inefficient.


You can call ISession.Refresh(obj) to force the object to be reloaded from the database. My understanding is that this will not refresh all relationships, so if you need to reload the complete object graph, call ISession.Evict(obj) then ISession.Get(id) to remove it from the cache and reload it.

0

精彩评论

暂无评论...
验证码 换一张
取 消