Change Tracking is a Real Deal in EF. Leverage It!!

These days modern automobiles are so sophisticated and mostly computerized, in that, we rarely need to see what’s under the hood.

When we work with Entity Framework, we take for granted that our LINQ queries will do the grunt work of translating LINQ queries to T-SQL or to the native language that a data provider understands, but, there’s more than meets the eye!

When you send a query to the database only to bring back say 10,000 records, you know well that you won’t be adding, updating or deleting records. In other words, all you’ll ever do is simply dump these records on a grid for the purposes of read-only. Why then, would you ever want to track your entities especially when you are going to be traversing through potentially thousands of entities for a LOB application. In this case, you are better off disabling your ChangeTracker. To do that, simply set the query to “AsNoTracking” and you are set. It is also worth noting that this particular scenario belongs to a State of Entity that is ‘Unchanged’. What it means is that the Entity exists in the database and it has not been modified on the client. Hence SaveChanges would ignore it.

In addition to ‘Unchanged’, there are three other ‘states’ of Entity which are the following:

  • Added: The entity does not exist in the database. SaveChanges should insert it.
  • Modified: The entity exists in the database and has been modified on the client. SaveChanges should send updates to the database.
  • Deleted: The entity exists in the database. SaveChanges should delete it.

Before we get into the nuts and bolts of Change Tracking, let’s first understand what is a Change Tracker? Well, to put it succinctly, change tracking is a process where Entity Framework keeps track of the changes you make to your objects.

So in the code snippet below, the code is marked as “AsNoTracking” which in essence turns off ChangeTracking on the query. As mentioned above, there is no practical use of a Change Tracker when all you are doing is retrieving records from the database. It is an overhead which should be avoided.

// Query some data
   var depts = db.Departments.Where(d => d.depID > 0)
         .AsNoTracking()
         .ToList();
         foreach (var item in depts)
         {
              Console.WriteLine("{0} - {1} - {2}", item.depID, item.depName, item.location);
         }         

You can also set the entity state directly using the DbContext.Entry method. See the following:

db.Entry(dept).State = EntityState.Unchanged;

 

The other option is to simply turn off Change Tracking at the Context level like so:

public class DepartmentContext : DbContext
    {
        public DepartmentContext()
        {
            this.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }
    }

In the code snippet below, one of the existing entities is being updated using DBContext in a disconnected scenario. It’s doing the following:
– Getting an existing Department from the database
– Updating the department name from “Accounting” to “R&D”
– Pass the modified entity to the Entry method and mark it as modified
– Call SaveChanges() in order to persist changes to the database

private static void UpdateDepartmentDisconnected()
        {
            using (var db = new DepartmentContext())
            {
                var dept = db.Departments.Where(d => d.depName == "Accounting").FirstOrDefault();
                if (dept != null)
                {
                    dept.depName = "R&D";
                }

                //save the modified data from above to a new context defined below
                using (var ctx = new DepartmentContext())
                {
                    ctx.Entry(dept).State = EntityState.Modified;
                    ctx.SaveChanges();
                }
            }
        }

There are some excellent resources that you can take advantage of:
Check out Arthur Vickers blog here and Julie Lerman’s blog here.

Posted in Uncategorized | Comments Off on Change Tracking is a Real Deal in EF. Leverage It!!

EF Core doesn’t support Stored Procedure mappings…Ok, So What!!!

While the above title is true to its core, however, you can still use stored procedures or for that matter raw SQL in EF Core 1.1. Here’s how:

Raw SQL:

private static void UseRawSql()
{
using (var db = new DepartmentContext())
{
var depts = db.Departments
            .FromSql("Select * from dbo.Departments").ToList();
foreach (var item in depts)
{
      Console.WriteLine("{0} - {1}", item.depID, item.depName);
}
   Console.ReadLine();
}
}

Stored Procedure:

    private static void UseStoredProc(int deptID)
    {
        using (var db = new DepartmentContext())
        {
            var depts = db.Departments.FromSql("Execute GetDepartmentByID {0}", deptID).ToList();
            foreach (var item in depts)
            {
                Console.WriteLine("{0} - {1}, {2}",item.depID, item.depName, item.location);
            }
            Console.ReadLine();
        }
    }

As you can see, the code is fairly straight-forward. All I am trying to highlight here is that you can leverage the “FromSQL” method to pass Raw SQL Queries or use Stored Procedure to bring back the result set, even without the support for stored procedure mappings in EF Core 1.1.

Mind you, EF Core is new. Going forward, with every release, EF Core will likely include a new set of feature(s), improvements et. al. This does not imply that everything that currently exists in EF 6.X, will automatically be added to EF Core!

EF team will attempt to add features that are crucial while features such as visual tooling, Entity SQL, Metadata Workspace API, EDMX Support etc. will a take a back seat. That being said, third party tools such LLBLGen Pro, devart are some of the tools that provide designer support with costs associated with it.

Posted in Uncategorized | Comments Off on EF Core doesn’t support Stored Procedure mappings…Ok, So What!!!

Using Code First in EF Core to spin an instance of DB in SQL Server

If you have been coding using Entity Framework 6.x, majority of what I am about to show you won’t come as a surprise with the exception of a few nuances.

Make no mistake…you can easily leverage your existing skill-set to create your POCO classes and DB Context class just as you have been doing in the past. Let’s try it with EF Core 1.0.

Create a new console app project in VS 2015. Select a Console App project. Install SQL Server database provider from inside Package Manager console window and type the following and hit enter: Install-Package Microsoft.EntityFrameworkCore.SqlServer

This would install the package and resolve dependencies for the package. It could take up to a couple of minutes before the installation is complete.

Add some code to your POCO class like so:
EFCorePoco

Create a context class and declare the DbSet of types. The only thing that you are required to do is to override a method called OnConfiguring(). This method takes in DbContextOptionsBuilder as an argument. The OptionsBuilder has a Use method called “UseSqlServer“. This is an extension method which becomes available after SQL Server database provider is installed. If it were Oracle, EF Core would create an extension method UseOracle and so on.

EFCoreContext

Couple things to note here…Notice the red circle in the figure below. This is a new API that the EF team at Microsoft has introduced which is called Database.EnsureCreated(). This allows Entity Framework to create a database that matches the shape of your entity. In our case, the Department and Employee classes for which it would create two new tables in the Demo.Department Database when the application code is executed!EFCoreMain

 

Now run the application. This would take about a minute to create the database and the tables, would add a record and output it to the console.

Output:EFCoreOutput

That’s all there is to it!

Hope you enjoyed this short and succinct tutorial on how to create a database using Code First in EF Core without running migrations.

Obi

Posted in Uncategorized | Comments Off on Using Code First in EF Core to spin an instance of DB in SQL Server

EF Core – What is it?

I have been meaning to write something on EF Core, a topic that is near and dear to my heart.

Microsoft has done phenomenal work in shaping this ORM what has turned out to be a real hot product, although the best is yet to come! In doing so, they have left no stone unturned in promoting EF Core in major conferences across the globe. This aggressive approach to this otherwise new technology has clearly resonated loud and clear amongst the developer community in particular and corporates in general. As a result, EF Core has already begun to gain traction.

Make no bones about it…EF Core is new and it’s still a version 1.0 product. Therefore, it wouldn’t be fair to compare it with its predecessor that has gone through numerous iterations for over eight years now.

So what exactly is EF Core (formerly EF7) and how is it different from Entity Framework?In Microsoft’s own words, Entity Framework (EF) Core is a lightweight and extensible version of the popular Entity Framework data access technology. EF Core is an object-relational mapper (ORM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.

The most current release of Entity Framework i.e. 6.1.3 is by far the most stable product we have seen yet! It has gone through eight plus years of development, bug-fixes and constant improvement thus providing a rich eco-system of data providers. These database providers are predominantly relational. Having said that there should be no doubt that Entity Framework is mature which offers a rich set of features such as Creating Model using Spatial data types, Many-to-many relationships, Visualizing a model, Alternating inheritance mapping patterns to Lazy Loading, Saving Data and Database Schema Management just to name a few!!

EF 6.x to EF Core is “Port” not an “Upgrade”

What it means is that there is no upsize wizard that can magically update all your Entity Framework project(s) to EF Core. Furthermore, EF Core does not support the EDMX file format for models. In order to port your model, your best bet is to reverse-engineer your model from the database for your application.

While EF Core is built with a lot of the same API’s, their implementation is totally different. For example, some of the common top level API’s such as DbContext, DbSet are still the same which in my opinion is a wonderful thing. Having said that, these top level API’s which are also part of EF Core are highly optimized and are guaranteed to give a significant boost when performing CRUD operations against a data store.

EF Core is made up of core components which in essence are a collection of loosely coupled services. There are categories of services ranging from Context, Provider specific, Design-time and User services.

Database Providers

Another important aspect of EF Core is that it can target a slew of data stores irrespective of whether they are relational or non-relational. Unlike Entity Framework which can only target relational databases namely, SQL Server, Oracle etc. EF Core can target these, but also target non-relational ones such Redis, In-Memory (for Testing) etc.

Which One is Right for You

Don’t be afraid to use EF 6.x if you are building an enterprise app. EF 6.x is tried and tested technology with many years of features, bug fixes and stabilization. However, if you are building an application that is cross-platform or if it targets ASP.NET core, then EF Core is definitely the right choice. The diagram below illustrates the platforms and App Models that EF 6.x and EF Core support.

NewPlatforms

Posted in Uncategorized | Comments Off on EF Core – What is it?

MVPMIX 2016 Toronto Technology Conference

Folks,

Due to popular demand, we are bringing MVP MIX 2016 to Toronto yet again!!

Seats are limited, so reserve your spot now. There will be two simultaneous tracks with sessions ranging from .NET, VS Code, ASP.NET Core, EF Core, JavaScript frameworks, Roslyn, Open Source, Cross-plat Apps with Xamarin and Azure, Document DB, Keno UI, Office 365, NuGet and more!!

We have a stellar line-up speakers who will enthrall you with their technical prowess and virtuosity.

MVPMIX2016Speakers

MVPMIX2016Speakers1See you on October 17th at the Canadian Microsoft’s Toronto Headquarters.

Obi

Posted in Uncategorized | Comments Off on MVPMIX 2016 Toronto Technology Conference