2
votes

Newbie Alert I am trying to check if an entity exists in the database, if it does i want to update it else create a new entity. But CreateCriteria use always returns an entity with no id? Any ideas why? I am using fluent nhibernate for manual mapping i.e use of ClassMap;

Base class -hold only the Id public property

public abstract class EntityBase : IEquatable { public virtual int Id { get; set; }

    public virtual bool Equals(EntityBase obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (GetType() != obj.GetType()) return false;
        return obj.Id == Id;
    }
}

MAPPING;

public class ProjectNameMap: ClassMap<ProjectName>
{
    public ProjectNameMap()
    {
        Table("dbo.TABLENAME");
        Id(x => x.Id).GeneratedBy.Identity();
        Map(x => x.PROJECT_NAME).Not.Nullable();
        Map(x => x.PROJECT_DESCRIPTION);
    }
}

Getting back the entity;

    public static T GetEntityByRestrictions<T>(String propertyName, String propertyValue)
                where T:EntityBase
    {
        using (var session = SessionManager.CreateSessionFactory().OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                var entity=  session.CreateCriteria<T>(propertyValue)
                                    .Add(Restrictions.Eq(propertyName, propertyValue))
                                    .UniqueResult<T>();
                return entity;
            }
        }
    }
}

Two silly steps i tried (dont laugh) 1. Silly step i tried was to manually set the Id =52 matching existing database entry and i keep on getting a primary key violation on project name as the database expects unique project name.

  1. More silly steps (i can hear laughter) modified mapping file to include Map(x=>x.Id).Update().Insert() and this lead to INSERT_IDENTITY set to OFF (or somethin).

So whats the best way to get an entity with Id and update afterwards,is there something wrong with my CreateCriteria?

1
Have you looked at the logs to see what queries it's actually running against the database?Cole W
You really don't want to be creating a new session factory every time you want an entity.James Gregory

1 Answers

0
votes

I believe calling the Merge method on the session will do exactly what you want.

Just put in the entity you want to update/insert as an argument and it will update the properties if the entity already exists or persist the new instance if it does not. This way you don't need the CreateCriteria and your solution will be a lot simpler.