Search code examples
c#nhibernatefluent-nhibernate

C# Fluent NHibernate Overview Mapping


I have three classes:

public class BaseEntity
{
    public int Id { get; set; }
}

public class DocumentOverview : BaseEntity
{
    public string Name { get; set; }
}

public class Document : DocumentOverview
{
    public byte[] Data{ get; set; }
}

In my application there is a tree and I want to load document names and list them there. Only when an TreeItem is selected I'm loading the Document entity to save traffic.

I don't want to have redundant code in my mapping, so my first attempt was like this:

public class DocumentOverviewMaps<T> : ClassMap<T> where T : DocumentOverview
{
    public DocumentOverviewMaps()
    {
        Table("Documents");
        Id(x => x.Id);
        Map(x => x.Name).Not.Nullable();
    }
}

public class DocumentMaps : DocumentOverviewMaps<Document>
{
    public DocumentMaps()
    {
        Map(x => x.Data).CustomType<BinaryBlobType>().Nullable();
    }
}

This does not work I always get the big Document entity even when loading overviews.

I found out that you can use SubclassMap<> but that doesn't work because it is for loading from different tables.

Is there any way to make this run without redundant code?


Solution

  • How about:

    public class DocumentBaseMap : ClassMap<T> where T : DocumentOverview
    {
        public DocumentBaseMap()
        {
            Table("Documents");
            Id(x => x.Id);
            Map(x => x.Name).Not.Nullable();
        }
    }
    
    public class DocumentOverviewMap : DocumentBaseMap<DocumentOverview>
    {
    }
    
    public class DocumentMap : DocumentBaseMap<Document>
    {
        public DocumentMap() 
            : base()
        {
            Map(x => x.Data).CustomType<BinaryBlobType>().Nullable();
        }
    }
    

    I'm wondering if the lack of the type parameter in your base class map is the reason why you only get the Document type? The empty DocumentOverviewMap class is a bit smelly. If it's the need for defined maps of the Document and DocumentOverview types that's the problem, then there's probably a better way to do this.