Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Loading in my C# app

I have a method in my DAL returning a list of Customers:

Collection<Customer> FindAllCustomers();

The Customer has these columns: ID, Name, Address, Bio

I need to show them in a paged grid in my ASPX form (show-customers.aspx) where I'll be showing only these columns: ID, Name

Now, in my DAL FindAllCustomers(), do I return the Bio field too from the SP (I am filling in the collection using a reader)? The Bio field can be large (nvarchar(max)). I was thinking of lazy loading or loading only the required fields. But then in that case I would need to create another method which returns a "full" list of customers including the bio so that 3rd party apps can use it through a service layer. So is it ok to create a method like this:

Collection<Customer> FindAllCustomers(bool loadPartial);

If loadPartial = true, then do not load Bio, else load it. In this case since I do not want to return the Bio from the SP, I would need to create 2 select statements in my SP based on the bool value.

I think using lazy loading here will not work, because then the DAL method can be accessed by a 3rd party app, which might want to load the bio too.

Any suggestions on the best pattern to implement in such cases?

thanks,

Vikas

like image 413
user154624 Avatar asked Dec 19 '25 00:12

user154624


1 Answers

The 3rd party thing is a bind.

At first blush I would normally suggest that you load only the minimal data normally and then load complete or further detail on an as-requested (i.e. touching a property could trigger a DB call - mild abuse of property there perhaps) or background process basis, depending on the nature of what you're doing.

Lazy property code by way of clarification:

class Customer
{
  private string _lazydata = null;

  public string LazyData
  {
    get
    {
      if (this._lazydata==null)
      {
        LazyPopulate();
      }
      return this._lazydata;
    }
  }

  private void LazyPopulate()
  {
    /* fetch data and set lazy fields */
  }
}

Be careful with this, you don't want to make lots of DB calls but nor do you want to be creating a bottleneck whenever you look at something lazy. Only the nature of your app can decide if this is suitable.

I think you have a valid case for creating the boolean flag method (though I would default to lightweight version) on the grounds that it's very likely a 3rd party would want the lightweight version for the same reasons you do.

I'd go with:

Collection<Customer> FindAllCustomers()
{
  return this.FindAllCustomers(false);
}

Collection<Customer> FindAllCustomers(bool alldata)
{
  /* do work */
}
like image 70
annakata Avatar answered Dec 21 '25 14:12

annakata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!