What does Connection Resiliency offer when using EF Core!

Connection Resiliency comes handy when you have a failed database operation. This operation could be the result of moving a database from one server to another for the purposes of load balancing, thus causing the database to become unavailable for a short period of time even if its for a few seconds.

Another scenario could be that you have deployed a database as a container and for some reason the container is not ready for other container(s) or micro-services etc.

In essence, Connection resiliency retries failed attempts in the event of database connection failure and is specific to relational databases. This feature was recently introduced as part of EF Core’s 1.1 release.

It’s implementation is fairly straight-forward. You need to define the execution strategy  by overriding the OnConfiguring() method in your dbContext or in Startup.cs if using an ASP.NET Core application.

Note the number 5 that I am passing to the EnableRetryOnFailure(5) which denotes of retries if the database commands were to fail. This method has two overloads which in addition to the number of retries, you can also pass in the delay between retries in milliseconds.

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"server=obi-oberoi; database=Demo.Department; Trusted_Connection=True;",
                options => options.EnableRetryOnFailure(5));
        }

Posted in ORM | Comments Off on What does Connection Resiliency offer when using EF Core!

What does EF Core give me out of the box?

As you might know, EF Core is brand new and it has long ways to go before reaching parity with EF 6.x, although some of the features that were murky in EF 6.x will probably never be added to EF Core.

That being said, it has some very good features that not only make the transition from EF 6.x to EF Core smoother, it’s also a lot of fun learning some of goodness of this otherwise new shiny tool.

Make no bones about it. EF Core is production ready and there are a lot features that you can already take advantage of. For example:

  • It’s constantly evolving and Microsoft is betting on it for its success going forward
  • It has the familiar APIs that we are used to like DbContext, DBSet etc.
  • It has full .NET Support in addition to being cross platform (can run on iOS, Linux, Android)
  • It is highly composable and hence lightweight
  • It is built from Ground Up and has APIs that highly performant
  • It supports Relational Databases and will have support for NoSQL databases in the future
  • The entire EF Core stack is open sourced on Github
Posted in ORM | Comments Off on What does EF Core give me out of the box?

Implementing Cascade Delete behavior in EF Core

The definition of Cascade Delete is if a record in the parent table is deleted, the corresponding records in the child table will automatically be deleted.

Now that we know what Cascade Delete is all about, let’s implement this behavior in EF Core where we will use Department and Employee tables. A Department can have one or more Employees. In other words, it’s a One to Many relationship. The idea is when we delete a record in the Department table, any references it has to the deptId key in the Employees table will also be deleted.

In the code that follows, the code loads records from the Department table and its corresponding Employees from the database. Notice the include method that is being used here. When SaveChanges is called, the cascade delete rules will be applied to the entities that are being tracked by the context.

Before Deletion:

CascadeDeleteBefore

private static void CascadeDelete()
        {
            using (var db = new DepartmentContext())
            {
                var depts = db.Departments.Include(e => e.Employees).First();
                db.Remove(depts);
                db.SaveChanges();
            }
        }

After Deletion:

CascadeDeleteAfterAs you can see DepID 8 which happened to be the first record in the Department table had two related Employees, namely, Rebecca D’Souza and Chris Wood. When the Department record with an Id of 8 was removed, it also deleted its corresponding Employees.

Since all Employees were tracked by the dbContext, the cascade behavior was applied before saving entries to the database. As a result, Entity Framework issued a DELETE statement for each of the matching entities.

Posted in ORM | Comments Off on Implementing Cascade Delete behavior in EF Core

Can I use Projections in EF Core…Absolutely!!

Before we drill into Projections, let’s find out what Projections really are:

Projection(s) is a powerful feature of LINQ that enables you to perform query operations on a data source, collection etc. It shapes the results of the data being queried into a different structure/format that the original data source is in.

It is a process to express queries in order to return a desired set of data other than the entire entity. Projection queries improve the efficiency of your application by only retrieving specific fields from your database.

A projection query lets you select only the data that is required from your model. It is done, by loading the data into a custom or anonymous type. This significantly improves the performance of your application, especially when you filter out the fields that contain huge amounts of data.

When you use the Select method, you can retrieve scalar properties and also navigation properties to retrieve data in the same query. Please see the code snippet below:

   private static void Projections()
        {
            using (var db = new demo_departmentContext())
            {
                var dept = db.Departments.Select(d => new { d.DepId, d.DepName, d.Location })
                    .Where(d => d.DepName.Contains("IT"))
                    .ToList();
                foreach (var item in dept)
                {
                    Console.WriteLine("{0} - {1} - {2}", item.DepId, item.DepName, item.Location);
                }
                Console.ReadLine();
            }
        }

And following is the output:

EFCoreProjectionsOutputAs  you saw above using projections allow us to retrieve a subset of the properties from an object as opposed to the entire object. This causes a smaller amount of data to be returned in the query.

Posted in ORM | Comments Off on Can I use Projections in EF Core…Absolutely!!

Using Migrations in EF Core

If you are an Entity Framework veteran who has worked extensively with EF 6.x and prior versions, then Migrations should come as no surprise to you!

The good news is that as you transition from EF 6.x to EF Core, Migrations are not much different to what you are used to using with EF 6.x. So it begs the question, how do I use Migrations in EF Core. Well, this is exactly what this article is about.

PM>add-migration init
To undo this action, use Remove-Migration.
PM>

This action would create a migration script as seen in the image below. Pay close attention to the Migrations folder in that the add-migration command created a migration file xxx_init.cs. It also created a ModelSnapshot. This file is used by Entity Framework to keep state of the current model which is then used to apply changes from your model to the database when migrations are run the next time.

In EF 6.x, when you run the add-migration command, the ModelSnapshot file is created in the database which makes it harder to version control this file in Source Control. So the EF team decided to lump this file with the migration file in the Migrations folder instead to facilitate version control.

1Migrations

 

public partial class init : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Departments",
                columns: table => new
                {
                    depID = table.Column(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    depName = table.Column(nullable: true),
                    location = table.Column(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Departments", x => x.depID);
                });

            migrationBuilder.CreateTable(
                name: "Employees",
                columns: table => new
                {
                    empID = table.Column(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    age = table.Column(nullable: false),
                    depID = table.Column(nullable: false),
                    empName = table.Column(nullable: true),
                    EmployeesempID = table.Column(nullable: true),
                    MiddleName = table.Column(nullable: true),
                    title = table.Column(nullable: true)
                },

As part of the migration file, it creates a bunch of code including the Down method below which is used in the event the migration needs to be restored to its previous state:

protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Employees");

            migrationBuilder.DropTable(
                name: "Departments");
        }

The next step is for the migrations update the database, but before that, let’s take a quick look at some of the EF Core commands:

EFCommands

You can also script the migration by simply using Script-Migration command which is also listed in the image above.

PM> script-migration

This will create T-SQL that matches the shape of your entity. You can then use this script to execute directly against SQL Server. This also gives the developer or the DBA some flexibility to tweak the script if necessary. If you rather not use the script-migration command, you are welcome to use the good’ol update-database command instead.

IF OBJECT_ID(N'__EFMigrationsHistory') IS NULL
BEGIN
    CREATE TABLE [__EFMigrationsHistory] (
        [MigrationId] nvarchar(150) NOT NULL,
        [ProductVersion] nvarchar(32) NOT NULL,
        CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
    );
END;

GO

CREATE TABLE [Departments] (
    [depID] int NOT NULL IDENTITY,
    [depName] nvarchar(max),
    [location] nvarchar(max),
    CONSTRAINT [PK_Departments] PRIMARY KEY ([depID])
);

GO

CREATE TABLE [Employees] (
    [empID] int NOT NULL IDENTITY,
    [age] int NOT NULL,
    [depID] int NOT NULL,
    [empName] nvarchar(max),
    [EmployeesempID] int,
    [MiddleName] nvarchar(max),
    [title] nvarchar(max),
    CONSTRAINT [PK_Employees] PRIMARY KEY ([empID]),
    CONSTRAINT [FK_Employees_Departments_depID] FOREIGN KEY ([depID]) REFERENCES [Departments] ([depID]) ON DELETE CASCADE,
    CONSTRAINT [FK_Employees_Employees_EmployeesempID] FOREIGN KEY ([EmployeesempID]) REFERENCES [Employees] ([empID]) ON DELETE NO ACTION
);

GO

That’s all there is to it. Hope you liked it!

Obi

Posted in ORM | Comments Off on Using Migrations in EF Core