Search code examples
wpfcollectionsfluent-nhibernatenhibernate-mappingnhibernate-collections

Fluent-Nibernate with wpf: Convention to use uNhAddIns...ObservableListType<T> as default?


I am trying to use Fluent-Nibernate with wpf that require Observable collections (implement the INotifyCollectionChanged interface).

At uNHAddins: Unofficial addins for NHibernate i found the

    uNhAddIns.WPF.Collections.Types.ObservableListType<T>

that implements INotifyCollectionChanged. It can be configured in Fluent-Nibernate like this

    namespace FluentNHibernateTutorial.Mappings
    {
        public class StoreMap : ClassMap<Store>
        {
            public StoreMap()
            {
                Id(x => x.Id);
                Map(x => x.Name);
                HasManyToMany(x => x.Products)
                 .CollectionType<uNhAddIns.WPF.Collections.Types
                                      .ObservableListType<Product>>()
                 .Cascade.All()
                 .Table("StoreProduct");
            }
        }
    }

Does anybody know how to implement a Convention with Fluent-Nibernate that always uses ObservableListType as default IList implementation ?

Update: The perfect solution would be something that does the replacement with Fluent-NHibernate-Automapper


Solution

  • Something like this should do the trick:

    public class ObservableListConvention :
        IHasManyConvention, IHasManyToManyConvention, ICollectionConvention {
    
        // For one-to-many relations
        public void Apply(IOneToManyCollectionInstance instance) {
    
            ApplyObservableListConvention(instance);
        }
    
        // For many-to-many relations
        public void Apply(IManyToManyCollectionInstance instance) {
    
            ApplyObservableListConvention(instance);
        }
    
        // For collections of components or simple types
        public void Apply(ICollectionInstance instance) {
    
            ApplyObservableListConvention(instance);
        }
    
        private void ApplyObservableListConvention(ICollectionInstance instance) {
    
            Type collectionType =
                typeof(uNhAddIns.WPF.Collections.Types.ObservableListType<>)
                .MakeGenericType(instance.ChildType);
            instance.CollectionType(collectionType);
        }
    }
    

    In response to the question update:

    This convention should work with the automapper like so:

    AutoMap.AssemblyOf<Store>(cfg)
      .Conventions.Add<ObservableListConvention>();