简体   繁体   中英

NHibernate (Fluent) mapping abstracting an intermediate class

I have a generic object type Entity and some classes that can relate to Entity such as EntityDescription and EntityLocation (many-to-one relationships).

Entity class:

public class Entity
{
    public virtual Int64 ID { get; set; }
    // and other properties
}

EntityDescription class:

public class EntityDescription 
{
    public virtual Int64 ID { get; set; }
    public virtual Entity Entity { get; set; }
    public virtual String Description { get; set; }
    // and other properties
}

EntityLocation class:

public class EntityLocation 
{
    public virtual Int64 ID { get; set; }
    public virtual Entity Entity { get; set; }
    public virtual String Location { get; set; }
    // and other properties
}

There are a number of more specific entity types eg Company, Supplier, Employee, etc. To make things more interesting, EntityDescription applies to all specific types, but only some types can be assigned locations (EntityLocation is only applicable to some types).

How do I map these classes in Fluent-NHibernate so that EntityLocation list is only exposed on some specific classes that can have locations (eg Company and Supplier), and not on the generic Entity class?

// This property can exist in Entity
public virtual IList<EntityDescription> Descriptions { get; set; }

// I want this property to only exist in some specific types, not in Entity
public virtual IList<EntityLocation > Locations { get; set; }

Any help appreciated. Thanks in advance.

I would say, that what we need is a ShouldMap setting. Check this answer:

FluentNHibernate - Automapping ignore property

So, we should introduce this configuration with different default handling of the Locations property:

public class AutoMapConfiguration : DefaultAutomappingConfiguration
{
    private static readonly IList<string> IgnoredMembers = 
                        new List<string> { "Locations"}; // ... could be more...

    public override bool ShouldMap(Member member)
    {
        var shouldNotMap = IgnoredMembers.Contains(member.Name);

        return base.ShouldMap(member) && !shouldNotMap;
    }
}

That will make the Locations property by default NOT mapped. Next step, is to use explicit mapping where needed...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM