tags:

views:

56

answers:

4

I have some classes in my app that don't require an ID to be persisted. These could be things like user logs or audit records. I can add an arbitaty id to them but I would like to avoid that as they don't mean anything.

The retrieval of these objects is always on another key (like UserId) which is not unique to the record.

A: 

If you want to be able to do CRUD operations on this records on the future, you may reconsider have an ID field.

Mendy
+1  A: 

I don't think you can avoid it. NHibernate details with "entities", rather than database rows and entities have an identity.

Consider what would happen if you were to read back some of those records, modify them and try to save them. NHibernate wouldn't know which database row to modify. Of course, you are not going to do that in your case, but this is exactly what NHibernate is designed to do.

So you would either needs to create an artificial ID or just save them without using NHibernate (ie. using direct SQL, which you can run via the NHibernate ISession object if you wish). If database space really matters (ie. you're going to have millions of these), I'd recommend the latter method, otherwise an artificial ID is pretty easy to add.

Evgeny
+2  A: 

Because NHibernate deals with entities, you must have something that identifies the entity. It is best to have a separate unique id field as that is the way the NHibernate is designed to work and it is much easier not to fight it.

However, if you have design constraints where you really can't have a separate id column, you can use a composite-id defined on existing fields. For example, for an audit log record you might use a combination of a UserId and a DateTime. If the records are only written once and not ever manipulated (e.g. audit log), you should also add mutable=false to the class mapping to enforce that. Also, be aware if you do use a composite-id like this it will likely cause issues if you ever try to use some of NHibernate's more advanced features with this entity in the future.

g .
+1 on composite ids although i use them heavily and i must say that issues are not so many...
Jaguar
A: 

You must have ID in some form. On my projects I just use composite-id on all fields of the entity, or whatever your composite key is in the database.

HeavyWave