0

I have a code that has to go through every item on a database and then decrypt what they pull back. I was told that lazy loading is a good way to go but I don't even know what it really is. I read up on it but I am still unclear. Below is the code that brings every item I need. How do I lazy load this so it doesn't bug down the system?

var potentialNumbers = _db.Owners.Where(x => x.UNQ4.Equals(submittedUNQ.Substring(submittedUNQ.Length - 4))).ToList().Select(o => o.UNQ).ToList();
rory.ap
  • 34,009
  • 10
  • 83
  • 174
BlowFish
  • 183
  • 3
  • 12
  • Assuming `UNQ4` is a `string`, no Lazy-Loading is involved here. Lazy Loading is only applicable for navigation-properties (and when you actually access them, not when you query on them). See https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx – haim770 Jan 24 '17 at 19:31
  • You need to post the code for your model too. – Sparrow Jan 24 '17 at 19:32
  • Start by removing all of the `ToList` calls that do nothing but inhibit what deferred execution is already happening, and force operations that *could* be performed by the DB to happen in your application. You're literally going out of your way to do extra work that accomplishes nothing useful, and actively inhibits what you're trying to do. – Servy Jan 24 '17 at 19:34
  • You may also consider [limiting](http://stackoverflow.com/questions/2656576/select-top-5-in-entity-framework) the amount of rows to select if it is appropriate. Though the best performance improvement you can get can be achieved by something like http://stackoverflow.com/questions/1323214/sql-server-index-on-a-computed-column – Eugene Podskal Jan 24 '17 at 19:38

1 Answers1

0

Lazy-loading in Entity Framework is turned on by default. You cannot force something to be 'lazily-loaded'. All you can do is turn off lazy-loading (which by the way, isn't actually eager-loading, it's 'no-loading'). So the answer is you can't. Indeed, however, as the comments have pointed out, if Owners class has a navigation property like, for instance,

public class Owners{
    public string UNQ4 {get;set;}
    public virtual OtherClass NavigationProperty {get;set;}
}

Then the NavigationProperty property will have a value of null initially when you do a query such as var owners = _db.Owners.First(). Later, when your program makes a call to owners accessing its NavigationProperty (like owners.NavigationProperty.Name), only then will a trip to the database be made to get the related NavigationProperty data.

Lazy-loading effectively does not load navigation properties until/if they are required. Good reference: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

coolboyjules
  • 2,300
  • 4
  • 22
  • 42