views:

304

answers:

3

Is it possible to use the guid.comb strategy for identity generation with Mysql Db using Nhibernate?

When I use it as

   mapping.Id(x => x.Id)
        .Column("row_guid")
        .CustomType(typeof(string))
        .GeneratedBy.GuidComb()
        .Length(36);

I end up with a

----> System.InvalidOperationException : Identity type must be Guid

Is there a way to overcome this obstacle in the MySql scenario?

Edit:
I don’t have a choice between guid and int. This is a port of a legacy db from MSSql

+2  A: 

I'm not convinced of the wisdom of using an unsupported data type for your primary key, but if you really do need to do this then you could try writing an NHibernate user type that exposes its property as a Guid but persists to the database as a string. The problem in this case seems to be that the property itself is defined as a data type other than System.Guid, which the guid.comb strategy expects.

I can't guarantee that it still won't error, but it's the only way you'll get it to work if it is possible. If you're new to NHibernate user types, there is an abstract base class that takes care of some of the drudge work for you here, with an example implementation class. You should be able to follow this example.

David M
Can you show a code sample please
Quintin Par
Post edited with a link that might help you.
David M
A: 

Just can use System.Guid as the type of the property.

O/RM is about mapping, so even though your database doesn't support a given type natively, you can still use this in your domain model. The underlying type of your column should be BINARY(16), for MySQL compatibility.

troethom
+1  A: 

This is common problem especially when porting MSSql applications to MySql.
As David said,implement a simple CustomIdGenerator which is a wrapper over GuidCombGenerator that gives you the Guid as a string.

using NHibernate.Engine;
using NHibernate.Id;

namespace NHibernateMaps
{
  public class GuidStringGenerator : IIdentifierGenerator
  {
    public object Generate(ISessionImplementor session, object obj)
    {
      return new GuidCombGenerator().Generate(session, obj).ToString();
    }

  }
}

And in the mapping specify it as

 mapping.Id(x => x.Id)
    .Column("row_id")
    .CustomType(typeof(string))
    .GeneratedBy.Custom(typeof(GuidStringGenerator))
    .Length(36);
Cherian