What is the best practice for readonly lists in NHibernate

后端 未结 5 1706
北荒
北荒 2020-12-06 02:32

Domain Model I am working on has root aggregate and child entities. Something like the following code:

class Order
{
   IList Lines {get;se         


        
5条回答
  •  庸人自扰
    2020-12-06 02:52

    I have spent several days looking for a best approach for readonly lists in NHibernate. This discussion helped me a lot to form the one that fits our project.

    There is an approach I started to use:

    1. Backing fields are used to store collections
    2. IEnumerable< T> is used to expose collections to force clients use AddLine() and RemoveLine() methods.
    3. ReadOnlyCollection type is used in addition to IEnumerable.

    Code:

    public class Order
    {
        private readonly IList lines = new List();
    
        public virtual IEnumerable Lines
        {
            get
            {
                return new ReadOnlyCollection(lines);
            }
        }
    
        public void AddLine(OrderLine line)
        {
            if (!lines.Contains(line))
            {
                this.lines.Add(line);
                line.Order = this;
            }
        }
    
        public void RemoveLine(OrderLine line)
        {
            if (lines.Contains(line))
            {
                this.lines.Remove(line);
                line.Order = null;
            }
        }
    }
    
    public class OrderLine
    {
        public Order Order { get; set; }
    }
    

提交回复
热议问题