Search code examples
configurationfluent-nhibernatefluent-nhibernate-mapping

DynamicUpdate in Fluent NHibernate doesn't work


In my application there are many cases where I have to update one single property of an entity in the database. In the internet I've read that DynamicUpdate() should change the behaviour of Fluent NHibernate so it does only update the properties != null

So I wrote my mapping like this:

public class Building
{
    public virtual Guid Id { get; set; }

    public virtual int ConstructionPhase { get; set; }

    public virtual string Name { get; set; }

    [some other properties]
}

public class BuildingMap : ClassMap<Building>, IMappedEntity
    {
        public BuildingMap()
        {
            DynamicUpdate();
            SelectBeforeUpdate();

            Id(x => x.Id);
            Map(x => x.ConstructionPhase);
            Map(x => x.Name);
            [some other properties]
        }
    }

But if I try to update an entity and leave the name property empty, the name is deleted in the database.

Do I have to configure Fluent NHibernate in an other way, or what's the problem?


Solution

  • DynamicUpdate() will instruct NHibernate to only save properties that have changed so loading the object, changing a single property and Flushing the session will only update the column that has changed.

    Update: to update single properties without going to the database use hql

    var affectedRows = session.CreateQuery("UPDATE MyEntity SET SomeProperty=:newValue WHERE Id=:id")
        .SetParameter("newValue", value)
        .SetParameter("id", id)
        .ExecuteUpdate();