Lazy loading - what's the best approach?

前端 未结 7 909
慢半拍i
慢半拍i 2020-12-31 07:22

I have seen numerous examples of lazy loading - what\'s your choice?

Given a model class for example:

public class Person
{
    private IList

        
7条回答
  •  再見小時候
    2020-12-31 07:51

    Here is an example implementing lazy loading using the Proxy pattern

    The Person class that would live with the rest of your models. Children is marked as virtual so it can be overridden inside the PersonProxy class.

    public class Person {
        public int Id;
        public virtual IList Children { get; set; }
    }
    

    The PersonRepository class that would live with the rest of your repositories. I included the method to get the children in this class but you could have it in a ChildRepository class if you wanted.

    public class PersonRepository {
        public Person FindById(int id) {
            // Notice we are creating PersonProxy and not Person
            Person person = new PersonProxy();
    
            // Set person properties based on data from the database
    
            return person;
        }
    
        public IList GetChildrenForPerson(int personId) {
            // Return your list of children from the database
        }
    }
    

    The PersonProxy class that lives with your repositories. This inherits from Person and will do the lazy loading. You could also use a boolean to check if it has already been loaded instead of checking to see if Children == null.

    public class PersonProxy : Person {
        private PersonRepository _personRepository = new PersonRepository();
    
        public override IList Children {
            get {
                if (base.Children == null)
                    base.Children = _personRepository.GetChildrenForPerson(this.Id);
    
                return base.Children;
            }
            set { base.Children = value; }
        }
    }
    

    You could use it like so

    Person person = new PersonRepository().FindById(1);
    Console.WriteLine(person.Children.Count);
    

    Of course you could have PersonProxy take in an interface to the PersonRepository and access it all through a service if you don't want to call the PersonRepository directly.

提交回复
热议问题