Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string keys in (fluent) NHibernate

I am working with brownfield database that uses strings as primary keys. Using Fluent NHibernate with Sqlite (in-memory provider for unit testing) and SQL Server 2005.

I have the following entity:

public class Entity
{
    public virtual DateTime TimeStamp { get; set; }

    public virtual string Name { get; set; }
}

With this mapping:

public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Map(_ => _.TimeStamp);
        Id(_ => _.Name).CustomType("AnsiString");
    }
}

However it does not work saying NHibernate.TypeMismatchException : Provided id of the wrong type. Expected: System.Int32, got System.String

How make this work? Also, is there any good documentation about fluent nhibernate available?

Thanks in advance.

like image 765
the_joric Avatar asked Mar 13 '12 23:03

the_joric


1 Answers

If you are using strings as your primary keys you'll probably have to do something like this:

public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Id(x => x.Name).GeneratedBy.Assigned();
        Map(x => x.TimeStamp);
    }
}

From the nhibernate documentation:

5.1.4.7. Assigned Identifiers

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.

Also here is a related article. It is a bit dated but still applies to your situation:

http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/6c9620b7c5bb7ca8

like image 190
Cole W Avatar answered Oct 22 '22 09:10

Cole W