Search code examples
c#nhibernateormnhibernate-mapping-by-code

Formula property update


good day everyone

i have some trouble with formula property, update and nhibernate

suppose, i have next model:

public class Model
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual State CurrentState { get; protected set; }
    public virtual ICollection<State> History { get; set; }

    public Model()
    {
        State = new List<State>();
    }
}

public class State
{
    public virtual Guid Id { get; set; }
    public virtual DateTime Timestamp { get; set; }
    public virtual string Description { get; set; }
    public virtual string Author { get; set; }
    public virtual Model Owner { get; set; }
}

and this is my mapping (NHibernate 4.0.0.4000, using mapping by code (not fluentnhibernate))

public class ModelMapping: ClassMapping<Model>
{
    public ModelMapping()
    {
        Id(x => x.Id, m => m.Generator(Generators.Assigned));
        Property(x => x.Name);
        ManyToOne(x => x.CurrentState, c => 
        {
            c.Formula("(select top(1) s.Id from State s where s.Owner = Id order by s.Timestamp desc)");
        });
        Bag(x => x.History, c =>
        {
            c.Cascade(Cascade.All);
            c.Key(k => 
            {
                k.ForeignKey("none");
                k.Column("ParentId");
            });
            c.OrderBy(x => x.Timestamp);
        });
    }
}

public class StateMapping: ClassMapping<State>
{
   public StateMapping()
   {
        Id(x => x.Id);
        Property(x => x.Timestamp);
        Property(x => x.Description);
        Property(x => x.Author);
        ManyToOne(x => x.Owner, c => c.Column("ParentId"));
   } 
}

now, i want retrieve some model entity (by knowing their id),

var model = modelRepository.Get(<someId>);

if i see model.CurrentState i see correct state (model.CurrentState = model.History.Last())

next, i try to add new state and save entity

model.History.Add(new State(){...});
modelRepository.Save(model);

after this content of model.History is ok (i see new state in collection and in database), but value of property CurrentState not updated (and equal to state at retrieving moment).

is there is any way to update formula property after entity was saved?


Solution

  • The only way to get the loaded entity to refresh is to call refresh or reload the entity.

    You History looks correct because you actually changed that state locally and sent the update to the server.

    Here's a relevant link. https://weblogs.asp.net/ricardoperes/nhibernate-pitfalls-entity-refresh