How to Build Trillion $ Opportunities & Solve the Grand Challenges of Humanity!

This is pretty much eleventh hour; and with a bunch of tickets on hand, I thought of making this final pitch to entice like-minded people to come and attend this once in a life time event.

This short seminar of 60 – 75 minutes could potentially change ones life and pave the road to ultimate Success!

WadhwaBlogUse this link to register for a complimentary seat.

I look forward to seeing  you on May 15th at 5:30PM at Microsoft Canada Headquarters.

Obi

Posted in News | Comments Off on How to Build Trillion $ Opportunities & Solve the Grand Challenges of Humanity!

Why is EF Core so blazing fast than its Predesessor?

It’s worth noting that EF Core is a brand new shiny tool from Microsoft that has been built from the ground up. It is lightweight, extensible and it comes with a plethora of new features when compared with EF 6.x.

Now, when it comes to performance, in just about all possible scenarios where tests have been conducted on CRUD related operations, EF Core has invariably outperformed EF 6.x. This is despite EF 6.x code having been tweaked for maximum optimization against somewhat naïve EF Core code, and yet coming out as a winner. So this begs the question…why is EF Core so much faster?

Well, the answer lies in the following:

  • Caching
  • Batching
  • Faster Initialization to build object models (conceptual model, mappings, storage etc.)

Stay tuned for more!!

Posted in ORM | Comments Off on Why is EF Core so blazing fast than its Predesessor?

EF 6.x or EF Core? I am confused!!!

If you are an enterprise developer or you are building a Line of Business Application and targeting the full .NET Framework and who also cares about visual tooling, EF 6.x is the way to go. It also means you can do WPF, Win Forms, ASP.NET MVC, Console apps etc.

EF 6.x is a mature product that is built over a period of time starting from 2008 till now. During this period, we have seen continuous improvements by way to adding new features, bug fixing etc. It has a rich eco-system of database providers and provides at least four workflows to build a model and database. It includes the following:

  • Code First
  • Code First From Database
  • Database First (EDMX Designer)
  • Entity First (Visual EDMX Designer)

EF Core on the other hand can target a multitude of application models ranging from full .NET Framework, ASP.NET Core as well as Xamarin. So if your dominant concern is to deploy your application on devices such as iOS, Android and such, EF Core is probably the way to go!

Apart from being cross-platform, EF Core is also a lightweight version of Entity Framework and is therefore built on a more leaner and faster development stack. Its because it has been built from ground up and is built over a set of services which make up the core of .NET.

Not only new platforms and new devices, EF Core has been architected to target new data stores. These data stores can be both relational and non-relational. Some of the examples of database providers are the following:

  • Azure Table Storage
  • Reds
  • In Memory (functional testing)
  • Relational providers such as:
    • SQL Server
    • SQLite
    • SQL Compact
    • Postgres
    • Oracle (prototyped)
    • DB2

more to come…

Posted in ORM | Comments Off on EF 6.x or EF Core? I am confused!!!

Can’t get too far without Transactions support. Guess what? EF Core’s got your Back!!

A transaction symbolizes a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in database.

If the transaction is committed, all of the operations are successfully applied to the database. If the transaction is rolled back, none of the operations are applied to the database.

The default behavior of a transaction is if the database provider supports transactions, all changes in a single call to SaveChanges() are materialized in a transaction. However, if any one of the changes fails, then the transaction is rolled back without any change(s) being materialized to the database. What this means is that SaveChanges() is guaranteed to either completely succeed, or leave the database in its original state in the event of a failure.

Let’s see this in action, but first, let’s see what we have in our database table called Departments before we call our method.

BeforeUpdateDelete

See the code snippet below. Notice SaveChanges() operation is being used twice. However, LINQ query is executed only once.

      private static void TransactionUpdateDelete()
        {
            using (var db = new DepartmentContext())
            {
                using (var trx = db.Database.BeginTransaction())
                {
                    int depId = 15;
                    var depts = db.Departments.Find(depId);
                    depts.location = "New Delhi";

                    //Delete a record
                    db.Database.ExecuteSqlCommand("delete from dbo.Departments where depId = 16");
                    db.SaveChanges();

                    var deptList = db.Departments.ToList();

                    foreach (var item in deptList)
                    {
                        Console.WriteLine(item.depName, item.depName, item.location);
                    }
                    Console.ReadLine();
                    trx.Commit();
                }
            }
        }

Snapshot of Data View After the Commit(). Notice DepartmentID 15 is updated from New York to New Delhi and DepartmentID 16 is yanked out as a result of the Deletion

AfterUpdateDelete

And lastly, the output window to demonstrate the successful execution of the two operations, namely, Update and Delete within the context of a Transaction in EF Core.

Output

Posted in ORM | Comments Off on Can’t get too far without Transactions support. Guess what? EF Core’s got your Back!!

I don’t see Visual Tooling in EF Core. What are my options?

Folks, some of the cool features/workflows that you are used to using in EF 6.x and with some of the prior versions such as Entity First, Database First that provide visual tooling are a thing of the past in EF Core.

Don’t despair; there’s hope. There are some third-part vendors that make tools which can be easily incorporated in your EF Core projects.

Some of the names of these companies are the following:
LLBLGen Pro: It is an entity modeling solution with support for Entity Framework and Entity Framework Core. It lets you easily define your entity model and map it to your database, using database first or model first, so you can get started writing queries right away. Apart from being one of the leading entity modeling solutions for .NET, it can be used with Entity Framework, NHibernate, Linq to SQL and our own ORM, the LLBLGen Pro Runtime Framework (included). It lets you easily define your entity model and map it to your database so you can get started writing queries right away.

LLBLGenPro

Telerik Data Access: If you’ve been a .NET developer, the odds are you’ve probably used at least one of the Telerik products, may it for the good ‘ol battle ship grey forms,  ASP.NET Web Forms, ASP.NET MVC, Mobile, Just Code, Fiddler etc.

Telerik

Telerik’s Data Access tools solve development problems with the most powerful data access framework. Some of the key features of the Data Access tool from Telerik bring you the following:

  • Mapping and Model Creation including the mapping of Stored Procedures & Functions
  • Change Tracking and CRUD Operations
  • Powerful Runtime Capabilities
  • Performance Optimization
  • Support for Multiple Databases
  • Unique Fluent API Capabilities
  • Data Access Profiler
  • Testability

More information can be obtained here.

DevArt: DevArt is another one of the ORM solution providers. It offers wide set of the .NET database connectivity tools with ORM support. It includes the following ORM tools and solutions:

  • Entity Developer
  • dotConnect
  • LINQ
  • LINQ Connect

DevArtMore information can be obtained here.

Posted in ORM | Comments Off on I don’t see Visual Tooling in EF Core. What are my options?

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