开发者

Readonly Strategies with Nhibernate and Fluent Nhibernate

开发者 https://www.devze.com 2023-04-05 02:07 出处:网络
I been reading nhibernate for beginners 3.0 and been reading about common mistakes(a few of them I been making)

I been reading nhibernate for beginners 3.0 and been reading about common mistakes(a few of them I been making)

I am wondering what are some strategies for making one or more records readonly. Right now I get all the rows back and loop through them making them readonly through session.Readonly().

I like in the book that they do with fluent

class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        SchemaAction.None();
        ReadOnly();

        // Mappings
    }
 }

What I am not sure is what happens if I need these records to not be Readonly? To me this means I have to make this exact same mapping minus those 2 lines of code.

开发者_如何学编程So I would like to do this and have ReadonlyEntityMap and EntityMap but I rather not have to duplicate all the settings twice.

Anyone have ideas on how do to this? Or better ideas for readonly?


Using ReadOnly() on your mapping will disable any updates back to the database when you modify the properties of the object.

If you want to apply some sort of ReadOnly and Writeable strategy I would suggest using a Fluent Convention and a marker interface or similar.

You can also apply ReadOnly() to a property if you want to disable writes on just that one property. I use that technique to avoid writing back to Computed Columns in SQL Server.

Something like this:

public interface IReadOnly{} //Mark entities with this interface

public class ReadOnlyConvention
     : IClassConvention, IClassConventionAcceptance<IClassInspector>
{
  public void Accept(IAcceptanceCriteria<IClassInspector> criteria)
  {
    criteria.Expect(x => x.EntityType Is IReadOnly);
  }

  public void Apply(IClassInstance instance)
  {
    instance.ReadOnly();
  }
}

Update: If you want to do you time conversion thing I would suggest creating an IUserType for your DateTime object which does the conversion to the user time without modifying the underlying data.

  • Date Time Support in NHibernate
  • Custom IUserType for DateTime


It depends on what you are trying to achieve. If you are trying to optimize memory consumption you should consider improving your session management strategy or using other performance improvement techniques. You can for example:

  • Clear the session that loaded your objects and it will release all the memory allocated by first level cache. The objects can later be reattached (Merged) to a new session if needed. This way you don't need objects to be readonly in the first place.

  • Evict some of the objects when you no longer need them. This will keep the other objects in the first level cache.

  • Use IStatelessSession which does not use 1st level cache at all.

Again, the answer depends on your application architecture.

0

精彩评论

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

关注公众号