Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate Generated AND Assigned ID Columns

I'm using Fluent NHibernate for my data-persistence in a web application.

My problem... I have a base class that maps all entities with an ID property of type T (almost always an int or GUID) using GeneratedBy().Identity()

On application start-up, I have a boot-strapper that checks and verifies the needed seed-data is populated. My problem is, some of the seed-data that is populated needs a specific ID. (IDs that would correspond to an enum or system user)

Is there any way to force NHibernate to commit the record using the ID that I specify, rather than an auto-generated one? Any other commits to the repository thereafter can be auto-generated.

like image 874
Adam Avatar asked Feb 19 '11 03:02

Adam


People also ask

What is the difference between NHibernate and fluent NHibernate?

Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.

What is NHibernate mapping?

NHibernate is an object–relational mapping (ORM) solution for the Microsoft . NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database.

What is projection in NHibernate?

The "projection" is kind of like plucking out what data you will need so that NHibernate only asks the database for just that data when it makes the SQL.


Video Answer


1 Answers

Id(x => x.Id).GeneratedBy.Assigned();

If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).

Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-id-assigned

like image 140
meir Avatar answered Sep 27 '22 21:09

meir