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.
- 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?