I'm experiencing a problem where NHibernate occasionally decides to
generate a new Guid id for my entity object and INSERT a new row rather
than UPDATEing an existing one.
The offending code gets an entity by id from the database (using
session.Get not session.Load), creates a new entity with a relationship to
the retrieved one, saves the new entity, then updates a property on the
retrieved entity and saves it. All saves are done via session.SaveOrUpdate.
Most of the time this executes as expected, an INSERT followed by an
UPDATE, but it occasionally decides to generate a new id during the second
SaveOrUpdate method and inserts a new row with the same values.
Can anyone suggest a likely cause for this?
var user = session.Get<User>(someId);
var action = new UserAction
{
SomeValue = 100,
User = user;
};
session.SaveOrUpdate(action);
user.SomeValue += 100;
session.SaveOrUpdate(user);
The above code is all executed on a single web request.
My entities look like this (simplified), and are being mapped with
FluentNHibernate auto mapping:
public class User : Entity<Guid>
{
public virtual int Version { get; set; }
public virtual int SomeValue { get; set; }
}
public class UserAction : Entity<Guid>
{
public virtual User User { get; set; }
public virtual int SomeValue { get; set; }
}
public abstract class Entity<TPk>
{
private TPk id;
public virtual TPk Id
{
get { return id; }
protected set { id = value; }
}
public virtual bool Equals(Entity<TPk> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (other.Id.Equals(default(TPk))) return false;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (!(obj is Entity<TPk>)) return false;
return Equals((Entity<TPk>)obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
Cheers
--Rory
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/nhusers/-/cBx-DI89Z_8J.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/nhusers?hl=en.