how to get id of entity using nhibernate createcriteria - fluent-nhibernate

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?

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.

Related

How can I successfully map a many to many table in nhibernate with a composedID and still save to it directly?

I have a bunch of GUID constants in my code for certain tag categories that are important in my application. This is mapped in a simple two column many to many table. I often want to avoid fetching the nhibernate object because all I really need is the GUID and it's already hardcoded. I also noticed it's much quicker and easier to do certain queries with direct table access. So, the goal is to to map those nhibernate many to many tables as a class so they can be read and written to without disrupting nhibernates usage of them in the regular sense; while at the same time using GUIDs for identifiers.
Anyway, I have settled on using a composedID across the two columns nhibernate generates. But there is a problem. If I use composed ID and make a Category tag object and try to save my TagID and CategoryTag ID directly, TagID gets saved to the CategoryTagID column and CategoryTagID gets saved to the TagID column!
public class CategoryTagMapping : ClassMapping<CategoryTag>
{
public CategoryTagMapping ()
{
Table("CategoryTag");
/*Id(x => x.ID, map => map.Generator(Generators.Guid));*/
Property(x => x.CategoryTagID, map => { map.Column("CategoryTagID");});
Property(x => x.TagID, map => { map.Column("TagID"); });
ComposedId(p =>
{
p.Property(p1 => p1.CategoryTagID, a => a.Column("TagID"));
p.Property(p1 => p1.TagID, a => a.Column("CategoryTagID"));
});
}
}
public class CategoryTag
{
/*public virtual Guid ID {get;set;}*/
public virtual Guid CategoryTagID { get; set; }
public virtual Guid TagID { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
return false;
var t = obj as CategoryTag;
if (t == null)
return false;
if (this.CategoryTagID == t.CategoryTagID && this.TagID == t.TagID)
return true;
return false;
}
public override int GetHashCode()
{
return (this.CategoryTagID + "|" + this.TagID).GetHashCode();
}
}
Trying to do this:
CategoryTag A = new CategoryTag { CategoryTagID = Constants.GUID1, TagID = Constants.GUID2 };
If I add the ID column by uncommenting the two lines, the saving works properly. But then that breaks the regular usage of the table because mysql can't auto increment the guid field and nhibernate won't generate an ID to go in the ID column.
Anyhow, maybe it's a bug, but maybe there's a workaround. Is there something wrong with the mapping, or the equals/gethashcode?
Thanks!
I am stupid. The columns are mismatched in the composedID mapping part.

Fluent NHiberate Automapping - inheritance per table not writing discriminator column

Using
NHibernate : 3.3.2
Fluent NHibernate: 1.3.0
.NET 4.0
Hi all, I'm trying to put together a (very) simple reference project for Fluent NHibernate using automapping, in particular setting up table-per-hierarchy inheritance. I've tried copying the config from an existing (working) project and I've run through the example on the Fluent Wiki page on AutoMapping and inheritance and both give me the same result; the base class that I've set up with table-per-hirearchy gets treated like a regular class.
The domain model looks like so:
namespace Tests
{
public abstract class Animal
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int Legs { get; set; }
}
public class Cat : Animal {}
public class Budgie : Animal {}
}
Like I said, simple, just to illustrate inheritance. I'm aware that 'legs' should probably be overridden on the base classes :)
The AutoMapping configuration looks like so:
public class AutoMappingConfig : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
var include = type.IsSubclassOf(typeof(Animal));
Debug.WriteLineIf(include, string.Format("Included {0} in NHibernate mapping.", type));
return include;
}
public override bool IsDiscriminated(Type type)
{
var result = type.In(
(typeof(Cat)),
(typeof(Budgie))
);
return result;
}
}
And finally, the configuration/session creation looks like so:
public static ISession NewSession()
{
var cfg = new AutoMappingConfig();
var map = AutoMap.AssemblyOf<Animal>(cfg)
.IgnoreBase<Animal>();
var dbConfiguration = MsSqlConfiguration.MsSql2008
.ConnectionString(ConfigurationManager.ConnectionStrings["testdb"].ConnectionString);
return Fluently.Configure()
.Mappings(m =>m.AutoMappings.Add(map))
.Database(dbConfiguration)
.BuildSessionFactory()
.OpenSession();
}
Putting that together, I try to create a couple of new records:
[Test]
public void CreateData()
{
var tiddles = new Cat {Name = "Tiddles", Legs = 4};
var kylie = new Budgie {Name = "Kylie", Legs = 2};
using (var transaction = _session.BeginTransaction())
{
_session.Save(tiddles); // exception!
_session.Save(kylie);
transaction.Commit();
}
}
}
The error is:
NHibernate.Exceptions.GenericADOException : could not insert:
[Tests.Cat][SQL: INSERT INTO [Cat] (Name, Legs) VALUES (?, ?); select
SCOPE_IDENTITY()] ----> System.Data.SqlClient.SqlException : Invalid
object name 'Cat'.
A few things to note:
The '?' are being filled out if I check with SQL Profiler.
When I put a breakpoint in the IsDiscriminated(Type type) method I can see that
its being called with the two expected types (Cat & Budgie) and is returning true each time. However, the SQL is writing to the wrong table, and its NOT writing a discriminator column. i.e. even though its been told that these classes are discriminated, they're not being treated as such.
In the table, the Id column is an auto-increment identity column.
I've tried adding other properties to the two sub classes in case they needed something other than just the base properties to trigger the correct behavior (no difference).
Any help would be greatly appreciated. I'm now convinced its something obvious, but no one here knows much about NHibernate (LightSpeed is another matter) so I've no idea what.
Ok, so the final working code looks like this:
public class AutoMappingConfig : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
var include = type.IsSubclassOf(typeof(Animal)) || type == typeof (Animal);
Debug.WriteLineIf(include, string.Format("Included {0} in NHibernate mapping.", type));
return include;
}
public override bool IsDiscriminated(Type type)
{
return typeof(Animal).IsAssignableFrom(type);
}
}
public static ISession NewSession()
{
var cfg = new AutoMappingConfig();
var map = AutoMap.AssemblyOf<Animal>(cfg)
.IncludeBase<Animal>();
var dbConfiguration = MsSqlConfiguration.MsSql2008
.ConnectionString(ConfigurationManager.ConnectionStrings["testdb"].ConnectionString);
return Fluently.Configure()
.Mappings(m =>m.AutoMappings.Add(map))
.Database(dbConfiguration)
.BuildSessionFactory()
.OpenSession();
}
And all is well with the world :)
(i.e. there were three errors)
The instructions here are a bit confusing, as it first talks about using .IgnoreBase<> so NHibernate wont treat the base as entity in its own right, then later mentions using .Includebase<> when using abstract layer supertypes. I'd tried both, but without Firo's answer got no luck.
you forgot animal
public override bool IsDiscriminated(Type type)
{
return typeof(Animal).IsAssigneableFrom(type);
}

fluent nhibernate: compositeid() of same types, getting message no id mapped

I've scoured Google and SO but haven't come across anyone having the same problem. Here is my model:
public class Hierarchy
{
public virtual Event Prerequisite { get; set; }
public virtual Event Dependent { get; set; }
public override bool Equals(object obj)
{
var other = obj as Hierarchy;
if (other == null)
{
return false;
}
else
{
return this.Prerequisite == other.Prerequisite && this.Dependent == other.Dependent;
}
}
public override int GetHashCode()
{
return (Prerequisite.Id.ToString() + "|" + Dependent.Id.ToString()).GetHashCode();
}
}
Here is my mapping:
public class HierarchyMap : ClassMap<Hierarchy>
{
public HierarchyMap()
{
CompositeId()
.KeyReference(h => h.Prerequisite, "PrerequisiteId")
.KeyReference(h => h.Dependent, "DependentId");
}
}
And here is the ever present result:
{"The entity 'Hierarchy' doesn't have an Id mapped. Use the Id method to map your identity property. For example: Id(x => x.Id)."}
Is there some special configuration I need to do to enable composite id's? I have the latest FNh (as of 6/29/2012).
Edit
I consider the question open even though I've decided to map an Id and reference the 2 Event's instead of using a CompositeId. Feel free to propose an answer.
I figured out this was due to auto mapping trying to auto map the ID
Even though i had an actual map for my class - it still tried to auto map the ID. Once i excluded the class from auto mapping, it worked just fine.

NHibernate, a different object with the same identifier value was already associated with the session

I have been working with NHibernate, using Fluent NHibernate for mapping. I solved a lot of issues, and started to think myself as experienced in nhibernate.
However, this error is quite strange.
This is my model:
public class MessageNew
{
public virtual int Id { get; set; }
public virtual string Content { get; set; }
public virtual string Subject { get; set; }
public virtual User User { get; set; }
public virtual bool IsSent { get; set; }
public virtual string AmazonMessageId { get; set; }
}
And my mapping
public class MessageNewMap : ClassMap<MessageNew>
{
public MessageNewMap()
{
Id(x => x.Id);
Map(x => x.Content).CustomSqlType("text");
Map(x => x.Subject);
Map(x => x.AmazonMessageId);
Map(x => x.IsSent);
References(x => x.User);
}
}
Here where exception occurs:
foreach (var userToSend in usersToSend)
{
string body = MailHelper.BuildSomeBody()
if (userToSend != CurrentUser)
{
MessageNew message = new MessageNew
{
User = userToSend,
IsSent = false,
Content = body,
Subject = subject
};
session.Save(message); // Exception thrown
}
}
The exception details:
NHibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: 1779, of entity: Models.MessageNew
at NHibernate.Engine.StatefulPersistenceContext.CheckUniqueness(EntityKey key, Object obj)
at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.Save(Object obj)
Id generator is database driven auto-increment id generator. (not hilo or any other). NHibernate version is 3.2.0 .
I have tried overloading Equals and GetHashCode, no luck.
The UnitOfWork pattern I am using requires not to commit transaction or flush session inside foreach loop. NHibernate says there is another object with same id, but all i am doing is inserting a new object, which does not have any identifier at all.
I am using the same structure all over my project, and it works well everywhere but this. I am suspicious that it might be because of "Content" property, which is text and set to a large string.
What am i missing here? Or NHibernate is missing something?
Sometimes it happend when we assign the object to the same new object. So first check your model and viewmodel that they are not same.
I had similar problem. I went through a lot of discussions, tutorials and forums, but after writing some unit tests, I realized:
1) session.Contains method works with instances
2)session.Save/SaveorUpdate works with ID
This error shows you have another instances of object with same ID in session.So, contains return false because you are working on different instances and Save/SaveorUpdate throws an exception because there is another object with same ID in session.
I've solved my problem like this(my problem was in Job Entity):
Job lJob = lSession.Load<Job>(this.ID);
if(lJob.ID==this.ID)
lSession.Evict(lJob);
lSession.SaveOrUpdate(this);
I hope it helps you
You can use Evict() to evict an object from a session and then you can do whatever you want.
This error occurs when you have the same object in another session.
messagenew should implement Equals and GetHashCode
public class MessageNew
{
public virtual int Id { get; set; }
public override bool Equals(object obj)
{
var other = obj as MessageNew;
return (other != null) && (IsTransient ? ReferenceEquals(this, other) : Id == other.Id;
}
private int? _cachedHashcode; // because Hashcode should not change
public override int GetHashCode()
{
if (_cachedHashcode == null)
_cachedHashcode = IsTransient ? base.GetHashCode() : Id.GetHashCode();
return _cachedHashcode.Value;
}
public bool IsTransient { get { return Id == 0; } }
}
I read some NH code. It basically inserts the new instance into the database to get its id. Then it checks if the id generated by the database is actually unique. If not, you get this exception.
Your database is not generating unique ids. You most probably forgot to set it to an IDENTITY column.
OR the identity starts counting on 0 instead of 1.
That exception usually indicates that you have 2 separate instances of an object with the same identifier value which you are trying to manage over the same session.
You already have another instance of the entity with that id.
Two possible issues:
1 - Your comparison of the entity does not work. You could override equals as suggested or you could change your test case that you use prior to the save:
if (userToSend.Id != CurrentUser.Id)
2 - You are not generating a unique Id for your entity, you need to either assign an Id yourself, have NHibernate generate one or have your sql server do it for you. In your mapping it is implied that an Identity should be used (Fluents default) but have you set up the column in your database to be and Identity column?
My take: you are not declaring an Id generator. Therefore, as soon as you get two MessageNew instances in the session, they'll both have 0 as the Id.
maybe a bit late but hope this helps.
I had a similar problem when i was trying to save multiple instances of an object over the same session with an auto generated column on them. My solution was giving a diferent value and assign it mannually for each entity, so nhibernates doesn't recognize it as the same primary key for that entity.
[..]
};
session.Clear();
session.Save(message);
Try this, helped me.
Add below two lines before Session.Save or Session.SaveOrUpdate
Session.Clear();
Session.Flush();
This will clear all cached entities with the Session.

No persister for... {SUBCLASS} NHibernate with Fluent NHibernate

How do I let NHibernate ignore extra properties of a subclass of my model?
class SuperModel { // hot I know
{
public Guid Id { get; private set; }
public string FirstName { get; set; }
}
class SubModel : SuperModel {
public string FavoriteColor { get; set; }
}
I really only want to store the SuperModel data using my repository and use the FavoriteColor elsewhere, but I get
No persister for: SubModel
even though I save it with my repository as
void Store(SuperModel model) {
using (var session = Session){
session.SaveOrUpdate(model); // <<<< The exception is thrown here
}
}
and some where else I use
void WhatToDo(SubModel model) {
doSomething(model.FavoriteColor);
}
And I use it as such
var model = new SubModel { FirstName = "Miranda", FavoriteColor = "Green" };
modelRepository.Store(model);
someService.WhatToDo(model);
Any one know how I can fluently configure this? Thanks.
FYI- implicit and explicit casting has no effect.
Edit
My mappings are like this
class SuperModelMap : ClassMap<SuperModel>
{
public SuperModelMap()
{
WithTable("SuperModels");
Id(x => x.Id);
Map(x => x.FirstName);
}
}
Edit 2
I figure/found out that I could do this, but in my database, I have to have a dummy table, which would just be inefficient. It works but there has to be a better way...
In my SuperModelMap...
JoinedSubClass<SubModel>("SubModel", MapSubModel);
private void MapSubModel(JoinedSubClassPart<SubModel> part)
{
// Leave this empty
}
Edit 3
I'm closer, but I still get a different error on selection.
I tried this.
DiscriminateSubClassesOnColumn("Id")
.SubClass<SubModel>(m => { });
InnerException {"Object with id:
5586b075-47f1-49c8-871c-9c4d013f7220
was not of the specified subclass:
SuperUser (Discriminator was:
'1000')"} System.Exception
{NHibernate.WrongClassException}
You can refine this solution to make it more reusable. As I understand, you don't like mapping duplication. This can be avoided:
I have created a SuperModelMapHelper class that contains an extension method:
public static class SuperModelMapHelper
{
public static void MapSuperModel<T>(this ClassMap<T> classMap)
where T : SuperModel
{
classMap.WithTable("SuperModels");
classMap.Id(x => x.Id);
classMap.Map(x => x.FirstName);
}
}
As you can see - it's generic and will accept any of SuperModel's subclasses. Then, there are two mappings:
public class SuperModelMap : ClassMap<SuperModel>
{
public SuperModelMap()
{
MapSuperModel();
}
}
public class SubModelMap : ClassMap<SubModel>
{
public SubModelMap()
{
MapSuperModel();
}
}
I've used extension method to preserve convention of FluentNHibernate, you can make it simple static method and pass class map as a parameter.
And this code:
Guid id;
using (var session = sf.OpenSession())
using (var transaction = session.BeginTransaction())
{
var subModel = new SubModel()
{FavoriteColor = "blue", FirstName = "Jane"};
session.Save(subModel);
id = subModel.Id;
transaction.Commit();
}
using (var session = sf.OpenSession())
using (var transaction = session.BeginTransaction())
{
var superModel = session.Get<SuperModel>(id);
Console.WriteLine(superModel.GetType().Name);
Console.WriteLine(superModel.FirstName);
transaction.Commit();
}
Works as intended - type is SuperClass. Note that I've created second session. You'd have to flush your session before trying to load entity in the same session you saved it, because NHibernate defers query execution.
Using this solution there is very little duplication. You can investigate AutoMapping feature of FluentNHibernate to reduce it even more - perhaps creating own convention would let you to automatically map such classes.
NHibernate assumes that you'd like to retrieve exactly the same object as you persist. So, even though you don't care about additional properties, you might care about the type of object. If you don't, the simplest solution would be to make a shallow copy of SubModel object, but instead of creating SubModel object, create SuperModel object.
I assume you thought about this and didn't like it. If you'd like to avoid dummy table, but can live with dummy column, I'd suggest you call:
DiscriminateSubClassesOnColumn("dummycolumn")
.SubClass<SubModel>(m => { });
This column would be used by NHibernate to store information about persisted object's type. When you load object from the db, it will be SubModel or SuperModel, depending on what it was when you persisted it.
Your solution with calling DiscriminateSubClassesOnColumn didn't work, because NHibernate couldn't determine which class to use based on id column.
Another idea: I'm not sure if it will work, but you could add another mapping, for SubModel, exactly the same as for SuperModel. Then, NHibernate should persist SubModel to the same table as SuperModel, and when you request your object it should fetch SuperModel object. Unfortunately I can't test this solution right now, maybe you can get it to work. No SubClass in this solution - two "parallel" mappings.