Eager, Lazy and Explicit Loading in Entity Framework Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign [Music] lazy loading and explicit loading in Entity framework core and when should you use them this is a common interview question and in order to answer that it is best to get some coding example my name is broken and welcome to dotnet mastery if you are new to the channel make sure to hit that subscribe button that way you will be notified when I upload new content now back to the main question what is lazy loading eager loading and explicit loading all of these concepts are related to loading the child elements when you have a parent and child entity with foreign key relation using Entity framework core to explain that with example let me build a small application with Entity framework core now I will not be going into the details of how to set up the application with Entity framework core but we will do all of that pretty quick and then dive into the main topic let me switch back to visual studio I will start fresh here let me create a new project I will select esp.net core web app MVC application and let me call that EF core loading I will keep the location that I have here and I am using.net 8. now with dotnet 8 I am using the preview version but if you want you can follow along in.net 7 as well we will keep everything simple and hit the create button first we need to configure Entity framework code in the application let me add nougat package for that I will have the include pre-release here but if you are using other version that is also okay we will install SQL Server let me do that and I want Microsoft dot Entity framework core dot tools perfect with that Entity framework code is configured in the project next we need to configure the application settings and I will add connection string right here we have a block there let me give it a name of default connection and I will paste my connection string if you have a different server here make sure to configure that I have a random database name here let me call that EF core loading that looks good next we need to configure program.cs to use the connection string and configure DP context we have to add that service in the container but I need to create a class that will Implement DP context first let me do that real quick we will implement the DB context here that is inside Microsoft dot Entity framework core and we need to pass the DB connection option here to the base class of DB context that is the default setting for Entity framework core now that we have created the class we can add Builder dot Services dot add DB context we will have the class application DP context here and in the option we will have use SQL Server we will extract the connection string and pass it right here now again this is default settings with ef core and I will not go into more details right there finally I want to create two models first model will be a villa model and inside there we will create few properties let me use the data annotation key for primary key let me create another class here which will be Villa amenity so basically each Villa will have few amenities and there will be a one-to-many relation between both the tables envela amenity we will have a villa ID and the navigation property for Villa on top of that we have name that is required that looks good now we have one-to-many relation right here in the Villa each Villa can have multiple Villa amenity we will add a collection of villa amenity that will establish the one to many relation between Villa and Villa amenity finally we need to create both of these tables I will create DB set for both of them here and let me see some records for Villa and Villa amnity we will overwrite the on model creating here perfect and there for the Villa we have has data we can populate some dummy records this is how you can seat The Villa table with records using migration let me create a dummy Villa here and let me create two more Villa properties and perfect that looks good with that we are creating three Villas in our record let me also create few Villa amenities I do not want you to waste time on watching me type that so let me paste that here and perfect you can see for Villa id1 we have four amenities four Villa id2 we have two amenities and Villa ID3 we have three different amenities that we added let me add a migration and get started I will call that create Villa and Villa number and see table perfect the migration is added it is creating table and it is populating data that looks good let me run the command update database and then let me switch to SQL Server Let me refresh the database here and we should have the new database that is EF code loading it has two tables and perfect both of them are populated so now we have records in both Villa and Villa amenity now our Focus will be to learn eager loading lazy loading and explicit loading let me switch back to the presentation here and first we want to see lazy loading in action and remember this is the default Behavior with Entity framework core let me open the controller here and we want to inject application DB context so let me do application DB context here I will call that underscore DB in the Constructor perfect we will be working on the index action method great initially let's say we want to fetch all the Villas that we have in our database so we want to load all the Villa here that is pretty simple the return type it will be an i enumerable of villa let me call that as well as using Entity framework core we can use the DP context and there we have all the DB set if we say underscore dp.village that will retrieve all the Villas and it will store that in the Villas variable it is simple as that next let's say here we want to count the total so we have total Villas is equal to villas dot count the default behavior of Entity framework code is on this line 21 it will not go to the database and retrieve the villa it will go and retrieve that only when something is accessing a property or accessing the Villas itself we are doing that on line 24 so that is when it will go to the database and fetch all the records let me show that if I run the application here it will also run a console application perfect you can see we have a console application and here it will display all the logs if you go to database the queries are also displayed by default with Entity framework core if I go back here and press F10 you will notice query is not executed in the console window on line 24 we are accessing the Villas and we are patching the count of villa at that point if I press F10 again you can see the query was executed that is known as deferred execution or lazy loading in Entity framework core on line 21 we wrote the command to retrieve all the Villas but once it is retrieved here it is not being used on this line that is why Entity framework code will differ the execution to a later point when that Villa is actually accessed and that is done on line 24 at that point it will go to the database and retrieve all the Villas count the number of records and assign that to Total Villas with that you have seen lazy loading in first example where it is the default behavior of Entity framework core it loads the data when it is accessed for the first time next point it does not load any child elements if you do not ask for it if I go back and examine the Villas here result view you can see the Villa amenity that is a child element of the Villa model and that is not populated because we have not explicitly asked for that so now the question is how do we load that Villa amenity that can be done in multiple ways let me stop the application here and we can have a for Loop where we are iterating through all the fillers based on the count here let me paste total Villas here for each of the records we want to populate Villas of I dot Villa amnity we cannot access the index here for that it has to be a list so right here let me convert that to list now because we are converting the underscore DB dot well as to list here at this point it will execute the query because we are altering the records that are retrieved previously when it was executing on count now it will go to database on the dot 2 list right here on velas of I we can populate Villa amenity we will make another database called tubular amenities and there we will have a wear condition using Entity framework core we want to say where Villa ID is equal equal to Villas of I dot ID I will convert that to a list here and perfect with that all the Villa amenity will be populated for each Villa let me run the application and show that perfect let me also minimize this and I will bring the console window here that way we can see all the locks perfect you can see on line 21 we have the query to retrieve all the villa in the for each Loop we have the execution to get Villa amenity based on the ID now that will be iterated three times because we have three Vela in total you can see we have four execution and basically this is n plus one problem if you want to retrieve and Records like here we have three records the total query execution will be n plus 1 that is four queries that are being executed right here and that is how lazy loading will work because we are loading the Villa amenity after we are loading the Villas if you examine the Villas now you will notice their Villa amenity is populated we have four we have two and we have three so that looks good but this is how lazy loading will work to load the child entities of villa if I go back to the presentation you can see multiple queries will be executed for the child elements that is how lazy loading will work I already mentioned that but I will mention that once again lazy loading is also known as default execution what we have here can also be simplified with a for each Loop if we are using a for each Loop let me comment this out we do not need the Villa total we can iterate through all the Villas here and directly load the Villa amenity like that that is much cleaner but if we run the project result will still be the same what I mean by that is if I open the console window you will still notice that we have n plus 1 execution for each Villa it is going to retrieve different Villa amenity populate that and perfect we are going to database four times to load the villas with their individual amenities now that you have seen lazy loading in action what is eager loading eager loading if I go back to presentation we will load all the data in one single request we have to use something called a start include method that is provided with Entity framework code and because we are loading all the data in one request eager loading will return a large amount of data as compared to Lazy loading finally because we will be loading everything in one database call there will be less query execution time to see that in action we will comment out the lazy loading here let me add a comment here lazy loading and we will have eager loading here for eager loading we will have list of villa that we want to retrieve let me call that eager underscore Villas is equal to underscore DB dot Villas and there we have something called as dot include in Microsoft dot Entity framework core and we can say U goes to U dot Villa amenity what this particular include statement will do is it will automatically include the navigation property based on the primary key and foreign key relation if I go to model here you can notice that in Villa amenity we have a foreign key of the Villa ID will be populated only verbilla ID matches for all the Villa amenity Formula 1 it will load the four amenities that we have for Villa 2 it will note the amenities where Villa ID will be 2 and so on Entity framework core will do all the complexity on how it Maps everything based on the foreign key relation now here we are using a different name if you want you can uncomment that that is also okay perfect let me run this and see what happens let me open the console window here first time we are retrieving all the Villas that gets executed now we are in eager loading where we will retrieve all the Villas on top of that we want to include Villa amnity if you press F10 here and examine the query you can see here along with Villa it is also left joining The Villa amenity that way it will retrieve all the details right here if you examine the records here you will notice that Villa amenities are also populated great with that you can see how easy and clean eager loading is as compared to Lazy loading the drawback here is of course it will return a large data but the main advantage is we get everything in single query execution as compared to the N plus 1 execution that we were facing in lazy loading if we continue here you can see it executed three more times because of the for each condition that we have so you can see how easy and Powerful eager loading is you can include multiple properties here if you want as well on top of that let's say Villa amenity also had a child element then in EF code we have a special extension called then include and that we can use to include any child properties inside the Villa amenity so that way we can go pretty fancy but we will keep things simple for now last thing that I want to cover is explicit loading and that applies to related data using explicit loading we will explicitly load the navigation property that means that it will not load the navigation property on the initial load and we can load a reference or a collection what I mean by that is if we go back and if we examine the Villa model here right now the navigation property that we have is a collection so how do we load that using explicit loading let me do that right here first one let me have that as explicit loading let's say we want to load only one Villa where the ID is one let me retrieve that using first or default then on the underscore DB we have a method that is entry and we will pass the Villa temp that we retrieved on this will attempt we have something called as a collection or a reference we need to populate a collection of villa amenity because of that we will use collection here and we will explicitly Define we want Entity framework core to populate the villa amnity and on there we will call the load method that will explicitly load the Villa amenity for this record let me add a debugging point and run the application let me examine the logs here perfect that is empty when I press F10 here it executes the select statement to retrieve Wella based on the id1 that is okay now at this point if you examine the Villa temp Villa amenity is not populated because we have not explicitly asked for that but here we are saying that hey on this will attempt I want you to figure out how to load the Villa amenity collection and populate that if I press F10 here you can see a query was executed to retrieve Villa amenities it retrieves that and now if you examine the Villa temp Villa amenity is populated so what we did on line 26 is explicit loading we have explicitly told Entity framework core that hey I want you to load a collection that is Villa right here let me show you an example to explicitly load a reference for that we will retrieve a villa amenity here and we will retrieve that from Willa amenities DB set if I go back to the database we have one and Villa ID is one as well what we will do is on the Villa amenity temp here we want to load the Villa navigation property if I go here you can see we have a navigation property in Villa amenity as well if I use a collection here it will not work because we have to load a single entity and for that we have to use reference with that let me run the application again and let me examine the logs here we go back and you will see something odd let me press F10 for the first two we are loading the collection and then when we are loading the Villa amenity or the ID of 1 if you press F10 and examine the Villa amenity temp to your surprise The Villa is also populated now it did not get populated on line 29. but right here when we were retrieving all the Villas Entity framework core already had that and that way it was smart to add that to our Villa amenity right here but if you comment that out and let me try again this time it will not be populated when we get the Villa amnity it is only going to Villa amenity and right here you can see Villa is not populated when we use the reference with explicit loading it retrieves that Villa and populates that right here write that in place you can see explicit loading using collection and reference now we have the main question on when should we use the individual options that we saw lazy loading is typically preferred when you are confident that you do not need to use the related entities instantly then we have explicit loading which works kind of like lazy loading but we can load that only after making a new explicit call to load the child entities explicit loading is very similar to Lazy loading when you compare everything because it is going to database again exactly like lazy loading is a use case for lazy loading or explicit loading would be let's say you have a collection of entities that you are retrieving and only for the top entity you want to load the child element if you are retrieving 100 records and if you only want child element for one record I will definitely use explicit loading or lazy loading in that scenario and then finally we have eager loading where we will load all the entities in one single call even though the call would be expensive as compared to Lazy loading I would still prefer that call in most of the scenarios and the reason is simple if I go back to my example here we have an action method where we have multiple execution the control will go back to the view after we load all the data it does not matter if on line 21 I use eager loading to load all the data or maybe I load the parent entity here and on line 41 we will go back to the database and retrieve all the child element that is a bad approach because now we are making n plus 1 database call in our example we were going to database four times using lazy loading or explicit loading but if I use eager loading it will join all the call and hit our database only once and that will be faster and you can see the code is also much cleaner but if you had an application where you are using HX call or Blazer where you can load more data once you scroll down on a page then lazy loading will make more sense that is what I have experienced working on multiple application for quite a few years now if you have some other scenarios where you have found lazy loading or explicit loading drastically beneficial let me know in the comments but like I said based on my experience with Entity framework core if someone will ask me to pick one in an interview I would always pick eager loading hands down unless I had a very good reason on how the other loading will be beneficial I hope this helps you to get an idea about the differences between eager loading lazy loading and explicit loading if you have enjoyed the video do not forget to like the video and leave a comment and if you have not subscribed to the channel make sure to do that right now that way you will be notified right away when I upload the next video I hope to see you guys in another video till then Happy coding
Info
Channel: DotNetMastery
Views: 1,683
Rating: undefined out of 5
Keywords:
Id: T9fTFynqvCw
Channel Id: undefined
Length: 27min 33sec (1653 seconds)
Published: Sat Jul 15 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.