简体   繁体   中英

c# Entity Framework loading entities

when i'm using entity framework does it create objects for all data in the database for example context.Customers.Load(); will it create 1000 customer objects and then 5000 order objects, and if so does it not use a lot of memory?

You should create the EF context from the moment you need it and dispose it from the moment you are done (unit of work, using statement). And of course, you should only query what you need - I doubt you need 5000 orders in one request.

And yes, EF creates entities for every query. Navigation properties are not loaded, you have to include these specifically or use lazy loading (but I would avoid this).

In addition to L-Three's response, using the using statement may not fit all circumstances. For example, with desktop applications, it makes more sense to keep the connection open instead of open and close connections all the time to query simple data. It is important to make sure you dispose of it when done though. A good place would be to listen for the Closing event on the window. When triggered, you could dispose of the DbContext .

If you don't reduce the scope of the query, eg: using a where clause, EF will load all the objects from the database when you try to access them. By doing var query = Db.Users; you aren't actually querying the database yet, you just created a query that will be sent when you try to access the data. If you did var query = Db.User.ToList(); , then yes, the query would be executed and all the User objects will be queried, mapped, and returned. So if you have 1 million rows, EF will try to load it 1 million records. In most cases, there is no reason to return all object from the database, but there are always fringe cases.

The child relationship is a little different depending on how you have the context configured. By default, I believe, EF uses something called lazy-loading . Lazy-loading allows EF to override your properties with a special code that won't load the child objects until you try to access them. On the other side of this, you can do what is called Eager-loading . This allows you to include all the child objects in the query as to make fewer trips to the database. In most cases, eager-loading should be used since you should know what information your application will be displaying to the user.

If you only ever use lazy-loading you can get into some trouble because it just works and it can cause performance issues down the road by creating n+1 statements for something simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM