开发者

NHibernate Cache Trouble

I have two entities having one to many relation and these are User and Address. One user can have many addresses. I am using one session and transaction per HTTP request pattern and Level 1 cache is turned on. For some reason I am seeing that my lazy loaded colle开发者_StackOverflowctions are not taking care of changes made to the data. For example If I create one user object. Then I create two address objects and save them like

User u1 = CreateNewUser("olduser@xyz.tld", "olduser@xyz.tld");
u1.Save();

Address a1 = CreateNewAddress(u1, "olduser@xyz.tld", "Old1", "User1");
a1.Save();
Address a2 = CreateNewAddress(u1, "olduser@xyz.tld", "Old1", "User1");
a2.Save();
Session.Flush();
Assert.AreEqual(2, u1.Addresses.Count); // THIS IS FAILING BECAUSE COUNT IS 0

Now when doing assert I am expecting user object to lazy load two address and count should be 2 but it returns 0. If I simply throw away complete cache by doing Session.Clear() call that doesn't work either. But if I throw away complete cache by doing Session.Clear() and then load my user object again this way it works as expected. I am not sure am I missing something or there is still something missing in NHibernate cache set-up configurations. Any help will be appreciated.

Thanks


You should add the addresses to the user object or refresh the user object (reload it from the database):

Session.Flush();
Session.Refresh(u1);
Assert.AreEqual(2, u1.Addresses.Count);


You will have to add the addresses to the user class too... Typically you see people creating a method u1.AddAddress(a1); which will set the reference to the user on the address object and add it to the address list in the user.


Default transaction type here is read committed, so you need a Flush() after each Save() or change the transaction type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜