Getting NHibernate to generate a HiLo string ID
We've got a large system that's loosely bound to its data source (Navision) via Unity - we're getting the opportunity to swap it out and have our own database.
So we've had a look around and really like the look of Fluent NHibernate - we're trying to get a proof of concept开发者_JS百科 going and swap out a couple of the services.
We want to use NHibernates HiLo algorithm - Unfortunately we've inherited string ID's from Navision which prefixs its ID's (example COL00001) so to match the Interface we need to use string Id's.
Does anyone know how I'd get something like ...
Id(x => x.ID).GeneratedBy.HiLo("100");
working where ID is a string? We're currently getting Identity must be int, long etc
Thanks,
Andy
------ Update ------
I tried the example in the article suggested but this functionality has been removed from later versions of Fluent NHibernate - there is however a .Custom - but I can't seem to get it working!
public class ManufacturerMap : ClassMap<Manufacturer>
{
public ManufacturerMap()
{
Id(x => x.ID).GeneratedBy.Custom(typeof(StringTableHiLoGenerator));
Map(x => x.Name);
}
}
public class StringTableHiLoGenerator : TableHiLoGenerator
{
public override object Generate(ISessionImplementor session, object obj)
{
return base.Generate(session, obj).ToString();
}
}
Finally cracked it ... thanks for your assistance - here's the solution in case anyone's interested...
Note: that in the Configure
method the IType
has to be passed to the base as an int
.
public class ManufacturerMap : ClassMap<Manufacturer>
{
public ManufacturerMap()
{
Id(x => x.ID).GeneratedBy.Custom<StringTableHiLoGenerator>(a => a.AddParam("max_lo", Nexus3General.HiLoGeneratorMaxLoSize.ToString()));
Map(x => x.Name);
}
}
public class StringTableHiLoGenerator : TableHiLoGenerator
{
public override object Generate(ISessionImplementor session, object obj)
{
return base.Generate(session, obj).ToString();
}
public override void Configure(IType type, System.Collections.Generic.IDictionary<string, string> parms, NHibernate.Dialect.Dialect dialect)
{
base.Configure(NHibernateUtil.Int32, parms, dialect);
}
}
I don't think you will manage to get the standard HiLo generator working with a string. Take a look at creating a custom id generator (which could be a hilo with a string):
http://nhforge.org/wikis/howtonh/creating-a-custom-id-generator-for-nhibernate.aspx
UPDATE regarding you update
I can't find any proper documentation regarding this in the fluent wiki. You could try this generic method though, rather than the method you are using:
Id(x => x.Id).GeneratedBy.Custom<IdentityGenerator>()
Does that work? If not I think your quickest response might come if you post on the fluent-nhibernate mailing list:
http://groups.google.com/group/fluent-nhibernate
The posted answer also worked in my case where i had a string as Primary Key with Custom Id Generator and Nhiberate was throwing the error: "type is not a ValueTypeType Parameter name: type".
精彩评论