Developers Club geek daily blog

1 year, 6 months ago
Recently we published article written by results of DEVIntersection conference visit. We bring to your attention one more useful "pressing" devoted to Entity Framework (EF).

ORM frameworks became for us usual tools for interaction with the database for a long time. In particular, if you are engaged in applications programming on the .NET platform, then, most likely, use Entity Framework, and not to surprise anybody with it any more. But, despite popularity of EF and abundance of information on him, quite often there is an incorrect understanding what is it why it is necessary and as it to use. In this article we will consider the most important, subjectively, features in Entity Framework 6.1.x. It is necessary to emphasize at once that EF will not solve all problems of interaction with the database, but nevertheless will help to get rid of many.

Migrations and initialization of the database


EF allows to generate classes of migrations, based on entities in a context which, in turn, implement methods Up() and Down(). It allows to move up and down the chain migrations, thereby managing the version of the database. Method Seed(DbContext) allows to add necessary data for initialization of base. It is excellent method to make quickly changes to the database, to react to new requirements or to solve problems.

Also we have an opportunity to migrate stored procedures, adding them to classes of migrations by means of a method AlterStoredProcedure. Many C#-разработчики with pleasure would refuse from hranimok because it is a little more difficult to support them. But from them not to get to anywhere as if to implement all operations in a code, then through what time the application will begin to work very slowly, and requests in base will be slowly executed.

Lazy loading automatically loads the automatic entities or collections connected directly with entity on which the request in the database is made. This approach has shortcomings connected with the fact that we literally pull out everything that is connected with records necessary to us, at this EF will place them in a context and will trekat changes of these records. To put it mildly, it 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 to load the necessary entities as part of request, using a method Include.

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

Explicit Loading — these are method to tighten obviously the necessary entities if Lazy Loading was disconnected.

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

System.ComponentModel.DataAnnotations (DataAnnotation) — a method of adjusting of model so that both EF, and ASP.NET MVC understood rules of setup. DataAnnotation allows to specify rules of validation or just to describe primary and foreign keys, using attributes ([Key], [RoreignKey], [Index], [StringLength], [Required], [NotMapped] and others).

System.Data.Entity.ModelConfiguration.Conventions (Code firs conventions) — a number of rules which are applied to model and describe it by means of the classes C#. It is possible to specify navigation properties, primary and foreign keys, difficult types.

Joint editing


There are cases when the same record is edited by several users. Let's say one only got record for editing, and another saved changes. After the first decided to save the changes, we will rewrite already changed records that can lead to loss of important data. Often nothing terrible occurs if just to apply last modifications.

By itself, there are several methods to solve a problem of simultaneous editing data. Let's consider Pessimistic and Optimistic concurrency.

Pessimistic Concurrency — one of methods of data loss prevention meaning blocking of entities. If someone already edits entity, then we will not allow other users to edit it therefore we do not need to think what records to save. This approach can cause a number of problems and slow down operation of application therefore it is supported by the few DBMS. In EF support of pessimistic concurrency is also not implemented.

As alternative to this method it is possible to consider Optimistic Concurrency. At this approach conflict situations are allowed and processed, and here EF can already help. The conflict can be processed by reaction on OptimisticConcurrencyException, the thrown Entity Framework, but at first it is necessary to teach EF to understand when there was a conflict. For this purpose it is necessary to add property by means of which it would be possible to monitor versions (as a rule, rowversion), and then to specify that it ConcurencyToken. It can be made through a method IsConcurrencyToken, having specified what property it is necessary to monitor.

Logging


Since EF 6 there was an opportunity to intercept the commands sent to the database. Thus, it is possible to implement logging, to change or cancel execution of commands. To property DbContext.Database.Log it is possible to appropriate the delegate who accepts a line as parameter. It will execute processing of this line, for example, just will save a log in the file or will display in the console. In fact, logging is just interception of commands and if it is necessary to implement own logic, then implementation is for this purpose necessary IDbCommandInterceptor, by means of which it is possible to subscribe for events and to do necessary operations with a database context.

Connection Resilency


If the Internet for some reason fell off, but EF at the same time executes request or saves changes, then now there is an opportunity to repeat once again. It is very useful feature if, for example, the base is hosted on Azure and with the Internet there can be problems. It is possible to configure with the help IDbConnectionStrategy.

* * *

Of course, it is not all features which to us are provided by EF. At first sight there can be an impression that they not such and important. However, as it seems to us, these features will be useful in any project and will give necessary flexibility and functionality in development process of applications.

This article is a translation of the original post at habrahabr.ru/post/273755/
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here: sysmagazine.com@gmail.com.

We believe that the knowledge, which is available at the most popular Russian IT blog habrahabr.ru, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.
Best wishes.

comments powered by Disqus