Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHIbernate automapping of List<string>?

Fluent NHibernate doesn't like this, throwing an error:

{"Association references unmapped class: System.String"}

OK fine, I can see why this would cause a problem - but what's the best solution?

I don't really want it to store a delimited list of strings in a single field, this would get ugly if my list contains many strings.

I also don't really want a table 'string', for obvious reasons.

I guess I can solve this by wrapping my List<string> inside a class, but this feels a little heavyweight. I'm starting to think its the best solution though.

What's the best way to get Fluent NHibernate to handle this?

I totally expect these values to be stored in another table. I thought perhaps that I may have been able to setup some automapping convention that instructs NHibernate 'If you see a class X that contains List<*some primitive type*>, then go ahead and automatically create a reference table that maps to this collection.

It feels a bit heavy to go and wrap every single collection in a class. If that is the best solution however, then so be it.

like image 801
Alex Avatar asked Dec 21 '09 19:12

Alex


1 Answers

I had this exact same issue a few weeks back, with floats instead of strings.

how-do-you-automap-listfloat-or-float-with-fluent-nhibernate

It turns out that Automapping does not work with primitive types.

Edit - This is no longer true - the FNH team has fixed the problem

There's a lot of sample code in the accepted answer to my question, but the key point is to add an override for your lists of primitive types ("RawY" in the example below):

public class DlsAppOverlordExportRunData
{
    public virtual int Id { get; set; }
    // Note: List<float> needs overrides in order to be mapped by NHibernate.
    // See class DlsAppOverlordExportRunDataMap.
    public virtual IList<float> RawY { get; set; }
}


// Must be in different namespace from DlsAppOverlordExportRunData!!!
public class DlsAppOverlordExportRunDataMap : IAutoMappingOverride<DlsAppOverlordExportRunData>
{
    public void Override(AutoMapping<DlsAppOverlordExportRunData> mapping)
    {
        // Creates table called "RawY", with primary key
        // "DlsAppOverlordExportRunData_Id", and numeric column "Value"
        mapping.HasMany(x => x.RawY)
               .Element("Value");
    }
}

I would expect the same approach to work with ILists of strings.

like image 138
Tom Bushell Avatar answered Sep 18 '22 16:09

Tom Bushell