Search code examples
c#nhibernatevirtual

Using virtual properties to support NHibernate proxies; ReSharper warns of virtual member call in constructor


I'm trying to support NHibernate proxying of my entities by marking the entities' properties as virtual:

public class Video : IAbstractDomainEntity<string>
{
    public virtual string Id { get; set; }
    public virtual string Title { get; set; }
    public virtual int Duration { get; set; }
    public virtual string Author { get; set; }
    public virtual bool HighDefinition { get; set; }

    public Video()
    {
        Id = string.Empty;
        Title = string.Empty;
        Author = string.Empty;
    }
}

ReSharper states that this is bad practice due to the issue described here: Virtual member call in a constructor

I understand the problem and I also understand that I cannot mark my class as sealed because then NHibernate would not be able to generate a proxy from the entity.

Do I just live with the waning and make sure not to do anything weird with my setters?


Solution

  • The best-practice is to use properties with backing fields:

    public class Video : IAbstractDomainEntity<string>
    {
        private string _id;
        private string _title;
        private string _author;
    
        public virtual string Id
        {
            get { return _id; }
            set { _id = value; }
        }
        public virtual string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        public virtual string Author
        {
            get { return _author; }
            set { _author = value; }
        }
        public virtual int Duration { get; set; }
        public virtual bool HighDefinition { get; set; }
    
        public Video()
        {
            _id = string.Empty;
            _title = string.Empty;
            _author = string.Empty;
        }
    }
    

    So you can avoid problems on child classes and you don't see any warning anymore