Programming to interfaces while mapping with Fluent NHibernate

后端 未结 5 1234
闹比i
闹比i 2020-12-01 01:22

I have been whipped into submission and have started learning Fluent NHibernate (no previous NHibernate experience). In my project, I am programming to interfaces to reduce

5条回答
  •  时光说笑
    2020-12-01 02:01

    I am having exactly the same issue. Unfortunately I have a valid reason for using entity interfaces; the entity model will be implemented in different ways and with different mappings per customer.

    The entire model needs to be read-only, so interfaces are of the style:

    public interface IAccount
    {
        long AccountId { get; }
        IHouse House { get; }
    }
    
    public interface IHouse
    {
        long HouseId { get; }
        HouseStatus Status { get; }
        IList Accounts { get; }
    }
    

    Concrete implementations then implement these with internal setters:

    public class Account: IAccount
    {
        public virtual long AccountId { get; internal set; }
        public virtual IHouse House { get; internal set; }
    }
    
    public class House: IHouse
    {
        public virtual long HouseId { get; internal set; }
        public virtual HouseStatus Status { get; internal set; }
        public virtual IList Accounts { get; internal set; }
    }
    

    I have gone down the route of mapping to the concrete classes. All is fine until you create relations which return interfaces and need to be cast to concrete implementations.

    HasMany(x => x.Accounts)
    

    can become

    HasMany(x => x.Accounts)
    

    But there is no equivalent 'cast' for

    References(x => x.House)
    

    Mapping to the interfaces (the neater solution) throws up the problem mentioned above in that the Id must exist on the topmost class for setting and requires a setter on the interface.

    public sealed class AccountMap : ClassMap
    {
        public PokerPlayerMap()
        {
            Id(x => x.AccountId, "account_id");
    
            DiscriminateSubClassesOnColumn("Type").SubClass(s =>  
            {
                References(x => x.House);       
            });
        }
    }
    

    For now, my only solution is to add setters to all of the interface Id fields. Its a shame the Id can't exist inside a subclass or have its type cast from the interface.

提交回复
热议问题