Question

I have the following class;

[ActiveRecord(Lazy = true)]
[DataContract]
public class Room : ActiveRecordBase<Room>
{
    [PrimaryKey]
    [DataMember]
    public virtual Int64 RoomId { get; protected set; }

    [Property]
    [DataMember]
    public virtual Int64 HotelId { get; set; }

    [Property]
    [DataMember]
    public virtual string Name { get; set; }

    [Property]
    [DataMember]
    public virtual string Description { get; set; }

    public static Room[] FindByHotelId(Int64 HotelId)
    {
        using (new SessionScope())
        {    
            return (Room[])Room.FindAllByProperty(typeof(Room), "HotelId", HotelId);
        }
    }
}

Although I'm using

new SessionScope()

When calling FindAllByProperty(), the database is always queried to get the data, rather than return the data from the cache.

If I call

Room.Find(1);

The response is given from the cache, with no query being made to the database.

Why is this happening, are there any Castle ActiveRecord experts that can help me ?

Was it helpful?

Solution

I'm no expert at Castle ActiveRecord but I guess that doesn't matter..

NHibernate uses a 1st level cache/identity map. When, you within a session, fetches the same object multiple times you are guaranteed to get the same instance back. In your case, this means that this assert should pass...

Assert.AreSame(
 Room.FindAllByProperty(typeof(Room), "HotelId", HotelId).First(),
 Room.FindAllByProperty(typeof(Room), "HotelId", HotelId).First())

However, the db query itself will be called everytime you make the call. This is true for any query except session.Get and session.Find (what these are called in Castle ActiveRecord I don't know).

If you want to start the queries themself you need to enable 2nd level caching. There is plenty of information about this on the internet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top