Question: proper way to implement lazy loaded collections in a domain model?

I have what I hope is a simple question but I suspect maybe not as there are probably multiple correct answers depending on the circumstance. I haven't done any programming for 5+ years and it seems like so many things have changed, so pardon if this question is a bit dumb.

Basically, I am just looking for a reasonable pattern to follow for building out an entity domain model, including relationships between objects, collections on objects, etc.

In the sample below I am showing a simplified Customer class on which I would like to expose an Orders collection. I would like to have the Orders collection lazy loaded by default, possibly with the option to eagerly load it when the calling code knows it will be using it. I'm planning to use Dapper for my data access, I specifically don't want to use a full on ORM like NHibernate.

I should maybe point out: the reason I have the class split into 2 partial classes in this example is because I plan to code generate the simple properties and then implement the object relationship classes by hand if I can't code generate. And if you're wondering why lazy loading: there are other scenarios more complex than this where there will be lots of associated collections, so for the sake of discussion let's assume it is a valid requirement.

What I would like advice on: according to current best practices, what would be the recommended way to implement the population of the Orders() collection in the example below, keeping in mind that I want to support lazy loading? In the olden days one would probably just write the code right there in the property to hit the database and load up the collection, but I suspect that would be considered wrong for more than one reason by today's design standards.

I've never used dependency injection before, is it considered an absolute must for this type of scenario, or extremely highly recommended? If so, I would very much appreciate a pointer to where I could best learn how to go that route. And if it isn't necessary, what would a proper non-DI-based implementation look like?

Preferably, I'd like to be able to instantiate objects very simply, like:

var custNew = new Customer(); var custExisting = new Customer(1); // lazy load collections var custExisting = new Customer(1, true); // load collection on instantiation 

That's just a preference, not a requirement.

Example Class

 public partial class Customer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } } public partial class Customer { // I want this to be lazy loaded: private List<Order> _Orders = null; public List<Order> Orders { set { _Orders = value; } get { if (_Orders == null) { // ?????????????????? } return _Orders; } } } 

Many thanks in advance.

by xt11111 via /r/csharp

Leave a Reply