Question

Is it possible to use a Fluent NHibernate convention to map all ICollections as sets? I have an entity like so:

public class NoahsArk
{
    public virtual ICollection<Animal> Animals { get; set; }

    public NoahsArk()
    {
        Animals = new HashSet<Animal>();
    }
}

With fluent mappings, this property would be mapped as HasMany(x => x.Animals).AsSet(), but how would I do this with a convention that I want to use with the automapper?

I should add that by default, ICollections get persisted as ILists, and I get a cast exception when it tries to cast the HashSet to IList.

Was it helpful?

Solution

This isn't possible in a convention, currently. If you want the automapper to treat your collections as sets by default, use ISet instead of ICollection.

OTHER TIPS

In response to Christina's question, you have to create a new class that implements IAutoMappingOverride<T>:

public class AlbumOverride : IAutoMappingOverride<Album>
{
    public void Override(AutoMapping<Album> mapping)
    {
        mapping.HasMany(x => x.Pictures).AsSet().Inverse();
    }
}

Then tell FNH to use it in the configuration:

Fluently.Configure()
    .Database(...)
    .Mappings(m => m.AutoMappings.Add(AutoMap.Assemblies(...)
        .UseOverridesFromAssemblyOf<Album>()))
    .BuildConfiguration();

You'll need a new override class for every entity you need an override for, but it's mostly a copy and paste affair.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top