这是一个使用代理模式实现延迟加载的示例
将与您的其余模型一起使用的 Person 类。Children 被标记为虚拟,因此可以在 PersonProxy 类中覆盖它。
public class Person {
public int Id;
public virtual IList<Child> Children { get; set; }
}
将与您的其他存储库一起使用的 PersonRepository 类。我在这个类中包含了获取孩子的方法,但如果你愿意,你可以在 ChildRepository 类中使用它。
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<Child> GetChildrenForPerson(int personId) {
// Return your list of children from the database
}
}
与您的存储库一起使用的 PersonProxy 类。这继承自 Person 并将执行延迟加载。您还可以使用布尔值来检查它是否已经加载,而不是检查 Children == null。
public class PersonProxy : Person {
private PersonRepository _personRepository = new PersonRepository();
public override IList<Child> Children {
get {
if (base.Children == null)
base.Children = _personRepository.GetChildrenForPerson(this.Id);
return base.Children;
}
set { base.Children = value; }
}
}
你可以像这样使用它
Person person = new PersonRepository().FindById(1);
Console.WriteLine(person.Children.Count);
当然,如果您不想直接调用 PersonRepository,您可以让 PersonProxy 接收到 PersonRepository 的接口并通过服务访问它。