Search code examples
c#nhibernatefluent-nhibernatefluent-nhibernate-mapping

NHibernate doesn't return auto-generated value after insert


I have the following entity

public class Entity{
   public virtual int Id { get; set; }
   public virtual DateTime CreatedDateTime { get; protected set; }
}

and I have the following nhibernate fluent mapping

public class EntityMap : ClassMap<Entity>
{
    public Entity()
    {
        Id(x => x.Id);
        Map(x => x.CreatedDateTime)
            .Not.Nullable()
            .Default("GETUTCDATE()")
            .ReadOnly();
    }
}

When I save this entity (with _session.Persist(entity)) into the database, it updates the generated id, but it doesn't update the CreatedDateTime value, although the CreatedDateTime gets generated correctly in the database. Is there any way to configure this entity to return also the auto-generated values after insert?

thanks


Solution

  • For your EntityMap mapping for your CreatedDateTime property, you can use the Generated property as in-

    Map(x => x.CreatedDateTime).Generated.Always();
    

    This will retrieve the UTC Date that was generated in your table row.

    Your sample code looks like some sort of id generator for your Entity table. It's not clear exactly where you are generating your Id field (on the client, or in the database). If you are generating your Id in the database, you can also modify your EntityMap to obtain the Id from the database-

    Id(x => x.Id).GeneratedBy.Identity();
    

    That will load your default initialized Entity object with the database generated Identity when you save the object (assuming your generating it from the database side).

    Hope that helps.