📜 ⬆️ ⬇️

Why I love so much EF, or features that are hard to give up

We recently published an article based on a visit to the DEVIntersection conference. We bring to your attention another useful "squeeze" dedicated to the Entity Framework (EF).

ORM frameworks have long become familiar tools for us to interact with the database. In particular, if you are developing applications on the .NET platform, you will most likely use the Entity Framework, and no one is surprised. But, despite the popularity of EF and the abundance of information about it, quite often there is an incorrect understanding of what it is, why it is necessary and how to use it. In this article we will look at the most important, subjective, features in the Entity Framework 6.1.x. It should be immediately emphasized that EF will not solve all the problems of interaction with the database, but it will still help get rid of many.

Database Migrations and Initialization


EF allows you to generate classes of migrations, based on the entities in the context, which, in turn, implement the methods Up() and Down() . This allows you to move up and down the chain of migrations, thereby controlling the version of the database. The Seed(DbContext) method allows you to add the necessary data to initialize the database. This is a great way to quickly make changes to the database, respond to new requirements or solve problems.

We also have the ability to migrate stored procedures by adding them to migration classes using the AlterStoredProcedure method. Many C # developers would gladly refuse to keep them, because maintaining them is a little more difficult. But you cannot get away from them, because if all operations are implemented in code, after what time the application will start to work very slowly, and requests to the database will be performed slowly.
')
Lazy loading automatically loads automatic entities or collections that are associated directly with the entity for which a query is being made to the database. This approach has drawbacks related to the fact that we literally pull out everything related to the records we need, while EF will put them in context and track changes to these records. To put it mildly, this can cause a number of problems and inconveniences.

 public class Category { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<Product> Products { get; set; } } 

Eager loading - allows you to load the necessary entities as part of the request using the Include method.

 var categories = context.Categories .Include(p => p.Products).ToList(); 

Explicit Loading is a way to explicitly pull up the necessary entities if Lazy Loading has been disabled.

 var category = context.categories.Find(1); context.Entry(category).Collection(p => p.Products).Load(); 

System.ComponentModel.DataAnnotations (DataAnnotation)
- a way to customize the model so that both EF and ASP.NET MVC understand the configuration rules. DataAnnotation allows you to specify validation rules or simply describe primary and foreign keys using attributes ( [Key], [RoreignKey], [Index], [StringLength], [Required], [NotMapped] and others).

System.Data.Entity.ModelConfiguration.Conventions (Code firs conventions)
- a series of rules that apply to the model and describe it using the C # classes. You can specify navigation properties, primary and foreign keys, complex types.

Co-editing


There are cases when several users edit the same entry. Suppose one just got a record for editing, and the other saved the changes. After the first one has decided to save his changes, we will overwrite already changed records, which may lead to the loss of important data. Often, nothing terrible happens if you just apply the latest changes.

Of course, there are several ways to solve the problem of simultaneously editing data. Let's look at Pessimistic and Optimistic concurrency.

Pessimistic Concurrency is one of the ways to prevent data loss, which involves blocking entities. If someone already edits the entity, then we will not let other users edit it, so we don’t need to think about which records to keep. This approach can cause a number of problems and slow down the application, so it is supported by few DBMSs. EF also does not support pessimistic concurrency.

An alternative to this method can be considered Optimistic Concurrency. With this approach, conflict situations are allowed and handled, and here EF can already help. A conflict can be handled by responding to an OptimisticConcurrencyException thrown by the Entity Framework, but first you need to teach EF to understand when a conflict has occurred. To do this, you need to add a property with the help of which you could monitor the versions (usually rowversion ), and then indicate that this is a ConcurencyToken . This can be done through the IsConcurrencyToken method, indicating which property should be monitored.

Logging


Starting with EF 6, it became possible to intercept commands sent to the database. Thus, you can implement logging, change or cancel the execution of commands. You can assign a delegate to the DbContext.Database.Log DbContext.Database.Log , which accepts a string as a parameter. It will process this line, for example, it will simply save logs to a file or output it to the console. In essence, logging is just interception of commands, and if you need to implement your own logic, then you need an IDbCommandInterceptor implementation with which you can subscribe to events and do the necessary operations with the database context.

Connection resilency


If, for some reason, the Internet has fallen off, but EF fulfills the request or saves the changes, now it is possible to repeat it again. This is a very useful feature if, for example, the database is hosted on Azure and problems may arise with the Internet. You can customize using IDbConnectionStrategy .

* * *

Of course, this is not all the features that EF provides us. At first glance, one might get the impression that they are not so important. However, it seems to us that these features will be useful in any project and will give the necessary flexibility and functionality in the application development process.

Source: https://habr.com/ru/post/273755/


All Articles