Is it possible to use NHibernate without altering a DDD model that is part of a framework

后端 未结 4 577
耶瑟儿~
耶瑟儿~ 2021-02-01 22:32

I dig a lot of things about the DDD approach (Ubiquitous language, Aggregates, Repositories, etc.) and I think that, contrary to what I read a lot, entities sho

4条回答
  •  春和景丽
    2021-02-01 23:32

    Just to put my two bits in, I struggled with the same thing once but I overcame this by:

    1. Adding protected default constructor to every entity.
    2. Making Id virtual

    Let's take for example upvote and downvote for Vote entity on my experiment website: http://chucknorrisfacts.co.uk/ (NHibernate + MySQL with Mono)

    public class Vote : Entity
    {
        private User _user;
        private Fact _fact;
        // true: upvote, false: downvote
        private bool _isupvoted;
    
        // for nHibernate
        protected Vote() { }
    
        public Vote(User user, Fact fact, bool is_upvoted)
        {
            Validator.NotNull(user, "user is required.");
            Validator.NotNull(fact, "fact is required.");
    
            _fact= fact;
            _user = user;
            _isupvoted = is_upvoted;
        }
    
        public User User
        {
            get { return _user; }
        }
        public Fact Fact
        {
            get { return _fact; }
        }       
        public bool Isupvoted
        {
            get { return _isupvoted; }
        }
    }
    

    This class inherits from Entity where we stick all the minimum necessary for Nhibernate.

    public abstract class Entity
    {
       protected int _id;
       public virtual int Id { get {return _id;} }
    }
    

    and Fluent mapping where you Reveal the private property.

    public class VoteMap : ClassMap
    {
        public VoteMap()
        {
           DynamicUpdate();
    
           Table("vote");           
           Id(x => x.Id).Column("id");
    
           Map(Reveal.Member("_isupvoted")).Column("vote_up_down");
           References(x => x.Fact).Column("fact_id").Not.Nullable();
           References(x => x.User).Column("user_id").Not.Nullable();
        }
    }
    

    You could probably place protected default constructor in Entity class and configure nHibernate to use it instead but I didn't look into it yet.

提交回复
热议问题