0

I'm retrieving an entity with an Guid Identifier from a database ... and I need to save entity to another database and keep the same Guid Identifier.Right now, NHibernate is generating a new Guid every time I perform a save operation, and this is normal, because I configured the mapping file for the entity in this manner. Is there any possibility that I can modify the mapping for my use case at run time?

Here is how I define my mapping for ID, and I want to keep it like this, if is possible.

 public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        Table("t_Order");
        Id(o => o.Id).GeneratedBy.GuidComb();
       .....
       .....
       .....
    }
 }

And here is how I try to change to IdentifierStrategyGenerator,but without effect, NHibernate assigns a new GUID for every save operation, and I'm losing the desired identifier.

  private void UpdateClientDatabase()
    {
        var key = HibernateMultipleDatabasesManager.Configuration
                                                   .GetClassMapping(typeof(Order)).Key as NHibernate.Mapping.SimpleValue;

        key.IdentifierGeneratorStrategy = "assigned";
        key.NullValue = "undefined";

        using (var session = HibernateMultipleDatabasesManager.DataSessionFactory("SQLiteDatabase").OpenSession())
        {
            _downloadedOrders.OfType<Order>().ForEach(_ => session.Save(_));
        }
    }
  • 1
    i know it's a little more work, but you could spin up 2 session factories with the different mappings. – Fran Nov 01 '16 at 13:20

1 Answers1

0

You could directly write an SQL statement as an exception. Copying an entity into another DB sounds like an exception to me.

Have a look at this answer for an example.

Session.GetISession().CreateSQLQuery("insert ....").ExecuteUpdate();
Community
  • 1
  • 1
renklus
  • 776
  • 6
  • 17