In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to load and control Loading Entities Entity Framework, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Entity Framework allows you to control the relationship between objects. In the process of using EF, we often do query operations. When we query, which data will be loaded into memory? Do you need all the data? It may make sense in some situations, for example, when the queried entity has only one related sub-entity, all the data can be loaded into memory. However, in most cases, you may not need to load all the data, but just load some of the data.
By default, EF loads only the entities involved in the query, but it supports two features to help you control the load:
1. Greedy loading
2. Delayed loading
The following explains the two loading methods in terms of the relationship between the three entities: customer type, customer and customer mail.
From the figure above, you can see the relationship between the three entity classes:
There is an one-to-many relationship between customer type and customer: a customer type can have multiple customers.
Customer and customer email is an one-to-one relationship: a customer has only one email address. (suppose there is only one email address)
1. Delayed loading (Lazy Loading)
Delayed loading: that is, data is loaded only when it is needed or used. By default, EF uses deferred loading to load data. Deferred loading is a process in which the relevant entities involved in a LINQ query are not loaded from the database until the results of the query are enumerated. If the loaded entity contains the navigation attributes of other entities, the related entities will not be loaded until the user accesses the navigation attribute.
Two conditions must be met to use deferred loading:
1. Entity classes are modified by Public modifiers and cannot be closed classes.
2. The navigation attribute is marked as Virtual.
1. Define entity classes
The CustomerType entity class is defined as follows:
Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace LazyLoding.Model {public class CustomerType {get; set;} public string Description {get; set;} / / Navigation properties are modified with the virtual keyword to delay loading public virtual ICollection Customers {get; set;}}
The Customer entity class is defined as follows:
Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace LazyLoding.Model {public class Customer {get; set;} public string Name {get; set;} / / Navigation attributes are modified with the virtual keyword to delay loading public virtual CustomerType CustomerType {get; set } / / Navigation properties are modified with the virtual keyword to delay loading public virtual CustomerEmail CustomerEmail {get; set;}}
The CustomerEmail entity class is defined as follows:
Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace LazyLoding.Model {public class CustomerEmail {get; set;} public string Email {get; set;} / / Navigation attributes are modified with the virtual keyword to delay loading public virtual Customer Customer {get; set Define the data context class and configure the entity relationship using LazyLoding.Model;using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks Namespace LazyLoding.EF {public class Context: DbContext {public Context (): base ("name=AppConnection") {} # region add domain entities to DbSet public DbSet CustomerTypes {get; set;} public DbSet Customers {get; set;} public DbSet CustomerEmails {get; set } # endregion protected override void OnModelCreating (DbModelBuilder modelBuilder) {/ / set table name and primary key modelBuilder.Entity (). ToTable ("CustomerType") .HasKey (p = > p.CustomerTypeId); modelBuilder.Entity (). ToTable ("Customer") .HasKey (p = > p.CustomerId); modelBuilder.Entity () .ToTable ("CustomerEmail") .HasKey (p = > p.CustomerEmailId) / / set entity relationship / * configure one-to-many relationship HasMany: indicates that a CustomerType contains multiple Customers WithRequired: required CustomerType cannot be empty MapKey: define the foreign key between entities * / modelBuilder.Entity (). HasMany (p = > p.Customers) .WithRequired (t = > t.CustomerType) .Map (m = > {m.MapKey ("CustomerTypeId") }) / * configure an one-to-one relationship HasRequired: indicates that the former must include the latter, and the former can exist independently The latter cannot exist independently WithRequiredPrincipal: it means that the specified Customer table is the primary table and can independently exist MapKey: define the foreign key * / modelBuilder.Entity (). HasRequired (p = > p.CustomerEmail). WithRequiredPrincipal (t = > t.Customer) .Map (m = > {) M.MapKey ("CustomerId") }); base.OnModelCreating (modelBuilder);}} 3. Use data migration to generate the database and override the Seed () method of the Configuration class to populate the seed data
The Configuration class is defined as follows:
Namespace LazyLoding.Migrations {using LazyLoding.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration: DbMigrationsConfiguration {public Configuration () {AutomaticMigrationsEnabled = false } protected override void Seed (LazyLoding.EF.Context context) {/ / This method will be called after migrating to the latest version. / / You can use the DbSet.AddOrUpdate () helper extension method / / to avoid creating duplicate seed data. / / initialize seed data context.CustomerTypes.AddOrUpdate (new CustomerType () {Description = "retail", Customers = new List () {new Customer () {Name= "Xiao Qiao", CustomerEmail=new CustomerEmail () {Email= "qiao@qq.com"}}) New Customer () {Name= "Zhou Yu", CustomerEmail=new CustomerEmail () {Email= "yu@126.com"}, new CustomerType () {Description = "e-commerce" Customers = new List () {new Customer () {Name= "Zhang Fei", CustomerEmail=new CustomerEmail () {Email= "zf@qq.com"}}, new Customer () {Name= "Liu Bei", CustomerEmail=new CustomerEmail () {Email= "lb@163.com"}}) 4. View the generated database
5. View the Main method and open the SQL Server Profiler Monitor to monitor the database / / the database has not been queried yet var customerType = dbContext.CustomerTypes
Continue to execute
View the monitor:
It is found that the SQL statement of the query is generated at this time.
This is the deferred loading technology of EF, which queries the database only when the data is actually used.
When using Code First, deferred loading depends on the nature of the navigation properties. If the navigation property is virtual modified, then deferred loading is turned on, and if you want to turn off deferred loading, do not add the virtual keyword to the navigation property.
Note: if you want to turn off deferred loading for all entities, you can configure the close attribute in the constructor of Context, as shown in the following code:
Public Context (): base ("name=AppConnection") {/ / configure to turn off delayed loading this.Configuration.LazyLoadingEnabled = false;} II, greedy loading (Eager Load)
Greedy loading: as the name implies, all the data is loaded at once. Greedy loading is a process in which when we load the main entity in the query, we also load all the entities associated with it. To achieve greedy loading, we use the Include () method.
Let's take a look at how to load all Customer data while loading CustomerType data (turn off deferred loading temporarily to avoid impact when doing this feature).
/ / greedy loading can be done in either of the following ways: / / when using the Lambda expression to indicate the navigation entity to load, refer to the namespace: System.Data.Entityvar customers = dbContext.Customers.Include (p = > p.CustomerType). Include (p = > p.CustomerEmail). ToList (); / / method 2var query = dbContext.Customers.Include ("CustomerType"). Include ("CustomerEmails"); summary:
Greedy load:
1. Reduce the delay of data access and return all the data in one database access.
2. Loading all the data into memory at one time may lead to the fact that some of the data is not actually used, resulting in slower data reading speed and lower efficiency.
Delayed loading:
1. Load only when you need to read the associated data. Each piece of data will access the database once, resulting in increased pressure on the database.
2. Performance may be degraded because of the delay in data access, because in the loop, each piece of data will access the database once, resulting in increased pressure on the database.
How to choose which query mechanism to use:
1. If you are loading data in a foreach loop, it is better to use delayed loading because you do not need to read all the data at once, which may result in multiple queries to the database, but it is basically within an acceptable range.
2. If you can foresee the need to load all the data at once, including all the data of the associated table, then greedy loading is a better choice, but this will lead to efficiency problems, especially in the case of a large amount of data.
The above is all the content of the article "how Entity Framework loads and controls Loading Entities". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.