5

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.

the_joric
  • 11,986
  • 6
  • 36
  • 57
  • Thx for links, though they neither are new for me nor contain anything related to my question :) I was not able to find anything about string keys there. Also I would like to start with explicit mapping. – the_joric Mar 14 '12 at 00:07
  • This is discussed in this link http://stackoverflow.com/questions/411825/nhibernate-with-string-primary-key-and-relationships – krystan honour Mar 14 '12 at 00:17
  • @krystanhonour not exactly. Also that question has no accepted answer. If you can recognize the answer there could you repost it here and get vote-up and my appreciation? Thx. – the_joric Mar 14 '12 at 00:31

1 Answers1

12

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

Cole W
  • 15,123
  • 6
  • 51
  • 85