In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Preface
The use of EntityFramework Core in the project is on-the-spot learning and use, timely find problems and timely testing, private use of leisure time will also learn other features that have not been encountered or used before, in this section we will talk about what new features have appeared in EntityFramework Core 1.1 for our use.
Discussion on the New Features of EntityFramework Core 1.1 DbSet.Find
There is also an implementation of this method in EF 6.x, and this method is also implemented in EF Core 1.1. why do you want to talk about it? of course, it also makes sense. Let's take a look. In
Public virtual T Find (int Key) {return _ context.Set () .Find (Key);}
At this point, let's query the data in Blog where the primary key is equal to 1.
Var blog1 = _ blogRepository.Find (1)
At this point, we get the following SQL through SQL Server Profiler monitoring.
We see that when querying data with a primary key equal to 1 through the Find method, we declare a variable and then set the value of the variable to query, there is no problem, the above we are directly achieved through the Find method, the following we use several other methods to achieve. As follows:
Public T GetSingle (int id) {return _ context.Set () .FirstOrDefault (x = > x.Id = = id);} var blog = _ blogRepository.GetSingle (1)
At this point, there is no difference from the SQL executed by the above Find method. Let's not jump to conclusions, and then let's take a look at the implementation through lambda expressions.
Public T GetSingle (Expression predicate) {return _ context.Set () .FirstOrDefault (predicate);} var blog = _ blogRepository.GetSingle (d = > d.Id = = 1)
At this point, let's look at the generated SQL statement.
At this time, the generated SQL statement without declaring variables looks very refreshing, and I have seen that the parameter in the lambda expression we declared in EF Core is the alias of our query table. I wonder if you have found it. Since there are many implementations above and it's cleaner to use lambda expressions, why come up with a Find method? read on.
Var blog = _ blogRepository.GetSingle (d = > d.Id = = 1); var blog1 = _ blogRepository.Find (1)
When we first query the data whose primary key is equal to 1, the second time we query through the Find method, by monitoring SQL Server Profiler, you will find that no SQL statement has been generated. What does this mean? it shows that the purpose of the Find method given by the EF Core team is: when the entity has been loaded into the context, when we query the data again through the Find method, we will not query the database at this time. So when we use the primary key to query data, using the Find method will reduce the number of requests to the database.
ICollection (collection type mapping support)
In previous EF versions, we used the following declaration fields
Public class Blog: IEntityBase {public virtual int Id {get; set;} public virtual string Name {get; set;} public virtual string Url {get; set;} public virtual ICollection Posts {get; set;}}
We know that the concept of delayed loading no longer exists in EF Core, so please use EF Core children's shoes to remove the virtual keyword. At the same time, we have always used the same ICollection when mapping collections, but there is no longer this limitation in EF Core. Let's define it as follows:
Public class Blog: IEntityBase {public int Id {get; set;} public string Name {get; set;} public string Url {get; set;} public IEnumerable Posts {get; set;}}
From the above we know that mapping of IEnumerable collections is now supported. Of course, there is a premise here that the concrete collection class must implement the ICollection interface, otherwise EntityFramework Core will not be populated.
Mapping to Fileds (map to field)
This feature should be unprecedented and can only be found in EF Core 1.1. let's take a closer look at the Backing Fileds (let's translate it into a return field for a moment). Since the emergence of the following automatic attributes, it has been a lot more convenient for us.
Public string Url {get; set;}
What is the return field (Backing Fileds) property? let's take a look at the original configuration of the field property as follows:
Private string _ url;public string Url {get {return _ url;} set {_ url = value;}}
The Backing Fileds feature allows EF Core to read or write data to fields instead of properties. That is to say, EF Core reads and writes data to the _ url field instead of Url as above. By default, the following four rules are configured as Backing Fileds.
_
_
M_
M_
For example, if the attribute is UserName, then the corresponding Backing Fileds is: _ userName,_UserName,m_userName,m_UserName. After Backing Fileds is configured, the corresponding data will be written directly to the field after querying the class instance from the database. At other times, when EF Core needs to read or write values, it is possible to use attributes. For example, when EF needs to update the value on an attribute, the set accessor of the attribute will be used. If the attribute is only read-only, then the value will be written to the field. For example, configure Backing Fileds, that is, _ validateUrl.
Class MyContext: DbContext {public DbSet Blogs {get; set;} protected override void OnModelCreating (ModelBuilder modelBuilder) {modelBuilder.Entity () .Property (b = > b.Url) .HasField ("_ validatedUrl");} public class Blog {private string _ validatedUrl; public int BlogId {get; set;} public string Url {get {return _ validatedUrl }} public void SetUrl (string url) {using (var client = new HttpClient ()) {var response = client.GetAsync (url) .result; response.EnsureSuccessStatusCode ();} _ validatedUrl = url;}
We can also configure whether to use attributes or fields in the mapping, as follows:
ModelBuilder.Entity () .property (b = > b.Url) .HasField ("_ validatedUrl") .UsePropertyAccessMode (PropertyAccessMode.Field)
If we have no attributes in the entity, we can store the data through fields at this time. We pass the Porperty (...) in the mapping. To specify the field name. If there is no attribute, EF Core will look for the field, as follows:
Class MyContext: DbContext {public DbSet Blogs {get; set;} protected override void OnModelCreating (ModelBuilder modelBuilder) {modelBuilder.Entity () .property ("_ validatedUrl");} public class Blog {private string _ validatedUrl; public int BlogId {get; set;} public string GetUrl () {return _ validatedUrl } public void SetUrl (string url) {using (var client = new HttpClient ()) {var response = client.GetAsync (url) .result; response.EnsureSuccessStatusCode ();} _ validatedUrl = url;}
After talking so much about Backing Fileds features, I don't know if you read this article and you know what its function is, why do you propose Backing Fileds features, and what is its value or purpose? as far as I understand it, most of the scenarios of Backing Fileds are: if the attribute is read-only, we need to obtain its value through other logical operations, but we don't have a bridge to assign it. At this point we need Backing Fileds to do it. If you have more opinions on this article, please leave a comment and discuss it together. Here we combine the above IEnumerable to further explain Backing Fileds. We have the following definition in the Blog class.
Public class Blog: IEntityBase {public int Id {get; set;} public string Name {get; set;} public string Url {get; set;} public IEnumerable Posts {get; set;}}
We know that the navigation property Posts is more likely to query the Posts through Inlcude, so here we don't need a set accessor at all to reduce the decompilation of Posts into Set methods, we can modify it as follows:
Public IEnumerable Posts {get;} = new List ()
Then again, in case we need to do something on Post, what should we do in this case? at this time, we expose the navigation attribute of IEnumerable, and then use the Backing Fileds of the navigation attribute to operate Post. The modification is as follows:
Public class Blog: IEntityBase {private readonly List _ posts = new List (); public int Id {get; set;} public string Name {get; set;} public string Url {get; set;} public IEnumerable Posts = > _ posts; public void AddPost (Post post) {/ / Do some buisness your logic _ posts.Add (post);}}
Let's actually do this, query the Blog data and navigate the attribute Post data.
Public virtual IEnumerable AllIncluding (params Expression [] includeProperties) {IQueryable query = _ context.Set (); foreach (var includeProperty in includeProperties) {query = query.Include (includeProperty);} return query.AsEnumerable ();}
We make the following enquiries:
Var blog = _ blogRepository.GetSingle (d = > d.Id = = 1, d = > d.Posts)
We modified the above a little bit, in order to avoid query errors, test the query, as follows, no problem.
Explicit loading (Explicit Loading)
It seems to explicitly load a scenario with no application, and I don't know whether it is given for some specific scenarios. It only loads the navigation attributes of the entity being tracked in context, which can also be implemented through Include, as follows:
Var blog = _ efCoreContext.Set () .Find (1); _ efCoreContext.Entry (blog) .Collection (b = > b.Posts) .Load (); _ efCoreContext.Entry (blog) .reference (b = > b.Posts) .Load (); connection elasticity (Connection resiliency)
The so-called connection elasticity means that we can try again when the database command fails. We can set it in OnConfiguring or Startup.cs, as follows:
Protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder .UseSqlServer ("connection string", options = > options.EnableRetryOnFailure ());}
SQL Server memory optimization table support
The memory-optimized table is a feature of SQL Server, which resides the entire table in memory and keeps a copy of the table on disk, mainly for persistence, and only reads the data in the memory-optimized table from disk when the database is recovered (such as reboot). For example, the memory optimization settings for the Blog table are as follows:
Protected override void OnModelCreating (ModelBuilder modelBuilder) {modelBuilder.Entity () .ForSqlServerIsMemoryOptimized ();}
Map entities to tables in memory optimization, and when you use EF Core to create a database based on our model, these entities will also create a copy in the memory optimization table.
Simplified Service replacement (Simplify switch services)
Service replacement can be implemented in EF Core 1.0, but it is slightly more complex. Replacing a service in EF Core 1.1 is similar to dependency injection, as follows:
Protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ("connection string"); optionsBuilder.ReplaceService ();
In versions prior to EF 6.x, circular references can easily be caused by the existence of navigation attributes, so for EF Core, we need to ignore circular references in Startup.cs, as follows:
Services.AddMvc () .AddJsonOptions (options = > options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
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.