views:

137

answers:

1

Dear ladies and sirs.

I am wondering how can one delete an entity having just its ID and type (as in mapping) using NHibernate?

Thanks.

P.S. I use NHibernate 2.1

+4  A: 

If you are using lazy loading, Load only creates a proxy.

session.Delete(session.Load(type, id));

With NH 2.1 you can use HQL. Not sure how it actually looks like, but something like this:

session.Delete(string.Format("from {0} where id = {1}", type, id));


Edit:

For Load, you don't need to know the name of the Id column.

If you need to know it, you can get it by the NH metadata:

sessionFactory.GetClassMetadata(type).IdentifierPropertyName
Stefan Steinegger
OK, but I cannot use this code as is, because it assumes I know the name of the Id column, which I don't. Is it possible given the actual entity CLR type, to locate the name of the Id column? After all it is in the mapping. Then, after obtaining the name of the Id column, I could execute the HQL. Thanks
mark
See my additional notes.
Stefan Steinegger
Almost there, but there is still a problem. Some entities define entity-name in their mapping, but not all. The entity type is always known. The problem is that GetClassMetadata returns null when given the type of an entity defining entity-name in its mapping. So, I get null when calling sessionFactory.GetClassMetadata(type). What am I to do? Thanks.
mark
As I see it, I must have entity-name at hand. Those entities without must supply their CLR type's FullName. Am I correct?
mark
AFAIK, there should be an overload which takes a Type as argument ?
Stefan Steinegger
There is, but it takes its FullName and delegates to the overload which takes a string, which in turn looks in a dictionary mapping entity-name to class metadata. Thus if an entity declares entity-name in its mapping, its metadata can only be obtained through the entity-name. Doing it by Type, like I did returns null.
mark
Yes, you're right. You need to pass the type fullname as entity name. You'll probably need to play around a bit. I think I have also a piece of code where I go through all the class meta data and read the original type from it, putting it to a static dictionary.
Stefan Steinegger
Thanks Sefan, this is exactly what I did - the dictionary mapping types to entity names. It looks very strange to me that an NHibernate user has to maintain such a dictionary, so I hoped there was a better way. Looks like there is none. Thanks.
mark
IF you write such generic code you need some common stuff between the entities, unless you need to write all this code. For instance, use an interface that includes the id, then you know its name. If you don't know it, you need to find out at runtime. it's like using reflection. Thinks can become complicates to cover many different cases.
Stefan Steinegger