May 2015

Volume 30 Number 5


Data Points - The EF6, EF7 and ASP.NET 5 Soup

By Julie Lerman | May 2015

Julie LermanMy January 2015 Data Points column, “Looking Ahead to Entity Framework 7,” highlighted what was coming in EF7 by looking at the state of the EF7 alpha at the time I wrote the article. In December 2014, just as that column’s issue was going to press, the EF team made an important decision about staging the EF7 releases. I managed to squeeze two sentences into the article at the last minute: “According to the post at bit.ly/1ykagF0, ‘EF7—Priorities, Focus and Initial Release,’ the first release of EF7 will focus on compatibility with ASP.NET 5. Subsequent releases will add more features.”

Since then, I found that sorting out what, exactly, this means to be a little confusing. I want to be sure you understand well enough what this initial release of EF7 targets, whether you should be using it and what your options are.

It will help to discuss the difference between the next version of the Microsoft .NET Framework and what ASP.NET 5 apps will run on. I’ll provide a high-level look, but check out Daniel Roth’s article, “Deep Dive into the ASP.NET 5 Runtime,” from the March 2015 issue to gain a more in-depth understanding. Then I’ll explain how EF6 and EF7 fit into the mix.

ASP.NET 5 (aka ASP.NET vNext) has been designed to have less reliance on the full .NET Framework and even Windows itself. Under the ASP.NET 5 umbrella, you can create Web applications and Web APIs using the new combined feature set in ASP.NET MVC 6, class libraries and even a console app. If you think of ASP.NET as a way to create Web sites, the console app is a mystery. But ASP.NET 5 is really providing a new “version” of the .NET Framework on which apps can sit. In fact, this new version currently has two flavors—one that runs on the full Common Language Runtime (CLR) and another that runs on the new CoreCLR. A third, which will run on a cross-platform CLR, will be added in the near future. The most streamlined version is called the .NET Core, which runs in a streamlined runtime, CoreCLR. If you think back to your early lessons on the .NET Framework, you might recall that Microsoft defined the Common Language Infrastructure (CLI), which is a specification. Then Microsoft built the CLR based on the CLI. Mono is another implementation of the CLI that runs on Linux and Mac OS X. .NET apps have always depended on the availability of a CLI implementation. Most of us have used Visual Studio and Windows to create .NET apps that depend on the CLR. Xamarin has become increasingly popular for developing apps that can run on Mono.

The CoreCLR and Entity Framework

Now, Microsoft has created a streamlined implementation of the CLI called the CoreCLR that’s not only open source, but also can be distributed by NuGet and other package managers. This gives developers the ability to create lightweight apps that are great for mobile devices and cloud-based server applications. And it also removes the constraint to deploy apps only to Windows machines.

Entity Framework 6 (and earlier) relies on the full .NET Framework and the full CLR, and won’t run with apps targeting the CoreCLR. But EF7 has been designed as a set of smaller, composable APIs that can be mixed and matched based on the feature set you need. For example, if you’re targeting a non-­relational data store, you don’t need the relational or migrations features that are designed for relational databases. With EF7, that logic is in a separate DLL that you won’t need to retrieve and load into memory.

When you choose to target the CoreCLR, you do so by selecting the correct runtime environment. To go with ASP.NET 5, Microsoft created the K Runtime Environment (KRE) that, as described by ASP.NET MVP Gunnar Peipman, “... is the code required to bootstrap and run an ASP.NET vNext application. The K Runtime will be renamed at some point before it’s released. Keep an eye out for this change. For example, the KVM (version manager) will become the DNVM (.NET Version Manager). The runtime includes things like the compilation system, SDK tools and the native CLR hosts” (bit.ly/1x9rpOn). There are 32-bit and 64-bit versions of the KRE that support the CoreCLR. You can see these as ASP.NET 5 application target options in Figure 1.

Selecting the Target KRE in an ASP.NET 5 Application
Figure 1 Selecting the Target KRE in an ASP.NET 5 Application

The easiest way to see EF7 in an application, outside of watching the demo video in my Pluralsight course, “Looking Ahead to Entity Framework 7” (bit.ly/18ct13F), is to use the ASP.NET 5 project template, which will give you a solution with EF7 already wired up to provide identity-based authentication to your application.

Start by choosing an ASP.NET Web Application and then the ASP.NET 5 Starter Web template, as shown in Figure 2.

Creating a New ASP.NET 5 Application with Entity Framework 7 Preconfigured
Figure 2 Creating a New ASP.NET 5 Application with Entity Framework 7 Preconfigured

You’ll find that the EF7 EntityFramework.SqlServer and EntityFramework.Commands packages are already selected. The SqlServer package will cause its dependencies (EntityFramework.Core, EntityFramework.Relational) to be pulled in.

You can see this in the project.json file, which lists the packages for NuGet to retrieve in its dependencies section. Here are a few lines from that section:

"dependencies": {
  "EntityFramework.SqlServer": "7.0.0-beta2",
  "EntityFramework.Commands": "7.0.0-beta2",
  "Microsoft.AspNet.Mvc": "6.0.0-beta2",

You can also see what ends up in the references section, which by default lists the references for the ASP.NET 5.0 and ASP.NET Core 5.0 versions of the application. Figure 3 shows the listing with the ASP.NET Core 5.0 references expanded. Note that because the template currently targets the beta2 version, you’ll see the Migrations package referenced, although in a later version, Migrations became part of the Relational API.

Both ASP.NET 5.0 and ASP.NET Core 5.0 References Contain Entity Framework 7 Packages and APIs
Figure 3 Both ASP.NET 5.0 and ASP.NET Core 5.0 References Contain Entity Framework 7 Packages and APIs

ASP.NET 5 and EF7 both embrace and rely heavily on dependency injection (DI). You can see in the project’s Startup.cs in Figure 4 that there is logic to let the app know it should use Entity Framework, its SQL Server API and the single predefined DbContext used for security, ApplicationDbContext. You can see this same context being wired up as the Identity service for the application. The connection string is stored in the config.json file and the Startup constructor wires up that file so the application will be able to find it when needed.

Figure 4 Partial Listing of Default Startup.cs

public class Startup {
  public Startup(IHostingEnvironment env) {
    Configuration = new Configuration()
      .AddJsonFile("config.json")
      .AddEnvironmentVariables();
  }
  public IConfiguration Configuration { get; set; }
  public void ConfigureServices(IServiceCollection services) {
    services.AddEntityFramework(Configuration)
      .AddSqlServer()
      .AddDbContext<ApplicationDbContext>();
    services.AddIdentity<ApplicationUser, IdentityRole>(Configuration)
      .AddEntityFrameworkStores<ApplicationDbContext>();
       services.AddMvc();  }

The project template now sets you up by default to use EF7 and to use its logic whether you’re targeting the streamlined CoreCLR or the full .NET Framework. In fact, by default, the project isn’t defined to run under the CoreCLR, but to use the full .NET Framework. So let’s look at where this option fits.

The Full CLR for ASP.NET 5 (and Entity Framework)

There’s an update to the .NET Framework coming, .NET Framework 4.6, and it will allow you to continue to create all of the styles of software you’ve been able to already—from Windows Forms and Web Forms to Windows Presentation Foundation (WPF) and ASP.NET MVC 5 apps. Thanks to the other KRE versions shown in Figure 1, KRE-CLR-amd64 and KRE-CLR-x86, it’s also possible to run an ASP.NET 5 application on top of the full .NET Framework. This lets you have your cake and eat it, too, if you want to benefit from other new features of ASP.NET 5, such as MVC 6 or the new Web API, which is a merger of MVC Controllers and Web API. It also gives you backward compatibility because you’re targeting the full .NET Framework and CLR and can access its full set of features. By default, the project.json file indicates you want to be able to run the application under either version of the CLR:

"frameworks": {
      "aspnet50": { },
      "aspnetcore50": { }
    },

You could remove the “aspnetcore50” line completely (along with the comma at the end of the previous line) and the effect would be twofold. First, the ASP.NET Core 5.0 section would disappear from References in Solution Explorer. Second, the KRE targets displayed in Figure 1 would be reduced to only the KRE-CLR options.

You’d still be targeting EF7 and getting all of the benefits of this new version. But, what hasn’t been obvious is that because KRE-CLR targets the full .NET Framework, it’s compatible with Entity Framework 6. This means if you have existing EF6 logic, it’s possible to use that in combination with ASP.NET 5 (though not the CoreCLR version), and gain the benefits of the new features of ASP.NET 5 without having to rework your EF6 code to align with EF7.

ASP.NET 5 (Full CLR) with EF6

Knowing this was possible, naturally I had to try to get EF6 into an ASP.NET 5 solution. Keep in mind that the approach I took to achieve this may very well need to change between the very early version I’m using right now (in February 2015) and when ASP.NET 5 and Visual Studio 2015 are released.

I found that the most important factor in achieving this was keeping the Entity Framework logic and dependencies in a separate project from the ASP.NET 5 project. I typically design my applications this way anyway, rather than having all layers of my app in a single project. With a separate project devoted to EF, you don’t have to worry about the ASP.NET 5 app pulling in EF7 APIs on the fly.

Rather than starting with the ASP.NET 5 Starter Web Project, you’re better off using the ASP.NET Empty Project template. The project.json file has only one dependency specified, Microsoft.Asp.NET.Server.IIS.

Next, you create a second project. I chose a .NET 4.6 Class Library project. I could then use the Package Manager Console to install EF6 by ensuring I was pointing to nuget.org as the package source and to the class library as the default project. At this point I was able to call install-package entityframework as I’ve always done. This brought entityframework.dll and entityframework.sqlserver.dll into the project.

To test, I created a simple class, Ninja.cs (because I think of EF6 as the Ninja edition, while EF7 is the Samurai edition):

public class Ninja {
    public int Id { get; set; }
    public string Name { get; set; }
  }

and a DbContext that exposed a DbSet of Ninjas:

public class NinjaContext : DbContext {
  public NinjaContext()
    :base(@"Data Source=(localdb)\mssqllocaldb;
          Initial Catalog=NinjaContext;
          Integrated Security=True;"){ }
  public DbSet<Ninja> Ninjas { get; set; }
}

For simplicity in testing, I’ve hardcoded the SQL Server connection string directly into my DbContext class.

With my model defined, I can enable migrations, add a new migration and create the database as I’ve always done. Note that when I installed EF6 into the data project, I left the app.config file that the package created so I could set that project as the startup project and then the migration commands would work correctly. I also used the DbMigrationsConfiguration Seed method to pre-seed the database with a few Ninjas.

I don’t want to make EF calls directly from the ASP.NET 5 application and create version confusion, so I have a class in my EF6 project that encapsulates the queries I’ll need. I’ve called it Repository because it suits my purpose, but this isn’t a class that follows the repository pattern. This isn’t challenging with a demo app and a single query, but you can use your favorite pattern for separation of concerns for more complex apps:

public class Repository  {
  public List<Ninja> GetAllNinjas() {
    using (var context=new NinjaContext())
    {
      return context.Ninjas.ToList();
    }
  }
}

With the data access project all set up, I can return to the ASP.NET 5 project. I’ve created a simple controller to retrieve and return a View:

public class NinjaController : Controller
  {
    public IActionResult Index()
    {
      var repo = new Repository();
        return View(repo.GetAllNinjas());
      }
    }
  }

I also created a simple Index.cshtml that will list the Ninjas passed in by the controller:

@model List<EF6Model.Ninja>
@{
  ViewBag.Title = "EF6 Ninjas";
}
@foreach (var item in Model)
{
  @Html.Label(item.Name);
}

Finally, Figure 5 shows code added to the startup.cs file, to inject the MVC services and specify routing to the Ninja controller.

Figure 5 Startup Class to Configure the ASP.NET 5 App That Uses Entity Framework 6

public class Startup  {
  public void Configure(IApplicationBuilder app) {
    app.UseMvc(routes =>
    {
      routes.MapRoute(
      name: "default",
      template: "{controller}/{action}/{id?}",
      defaults: new { controller = "Ninja", action = "Index" });
     });
  }
  public void ConfigureServices(IServiceCollection services)  {
    services.AddMvc();
  }
}

I also removed the aspnetcore50 framework from the project.json file, ensuring that I only target the full CLR.

With the database and some seed data created by migrations, I’m able to see the ASP.NET 5 app working with the EF6-based project, displaying data that was retrieved using EF6 (see Figure 6).

ASP.NET 5 Application Displaying Data via Entity Framework 6
Figure 6 ASP.NET 5 Application Displaying Data via Entity Framework 6

Will I Be Using EF7 and ASP.NET 5 Right Away?

I’m very interested in the new capabilities of EF7 and in learning how to best leverage them. I’m also looking forward to understanding this new avenue of programming that ASP.NET 5 opens. The CoreCLR will become richer as it evolves, as will EF7. I’m impressed with the state of EF7 as it will be released with ASP.NET 5. But because I’m not a Web developer, I don’t have a reason to work in production code at the bleeding edge of ASP.NET, and the EF team has been clear that it recommends using the initial release of EF7, which will be marked as a prerelease, only with ASP.NET 5 applications. Otherwise, the team’s guidance is to wait until EF7 is released as a true version. Therefore, I may well wait for the subsequent releases of EF7, but continue to follow and experiment with the project as it evolves to gain more parity with the features of EF6 that I might otherwise miss.

The CoreCLR is currently too bleeding edge for my tastes. If I find a scenario that fits what will be available in the full CLR release of ASP.NET 5, as well as the feature set of the EF7 prerelease, then I’ll be eager to take that path. It’s more likely, however, that I’ll end up waiting for the subsequent releases. And by then ASP.NET 5 and the CoreCLR will be richer, too. For me, personally, the time until then will provide a chance to explore and learn about these tools in preparation for the later release.

In the meantime, I highly recommend reading Scott Guthrie’s blog post, “Introducing ASP.NET 5,” at bit.ly/1wV4zzm to have a better understanding of all of the new features that ASP.NET 5 brings. The composable APIs are only one of many exciting improvements that developers will gain in this shift.


Julie Lerman is a Microsoft MVP, .NET mentor and consultant who lives in the hills of Vermont. You can find her presenting on data access and other.NET topics at user groups and conferences around the world. She blogs at thedatafarm.com/blog and is the author of “Programming Entity Framework” (2010), as well as a Code First edition (2011) and a DbContext edition (2012), all from O’Reilly Media. Follow her on Twitter at twitter.com/julielerman and see her Pluralsight courses at juliel.me/PS-Videos.

Thanks to the following technical expert for reviewing this article: Rick Strahl
Rick Strahl is the Big Kahuna at West Wind Technologies, located on the beautiful island of Maui, Hawaii. Between windsurf sessions and spikey-haired adventures, Rick has been a software developer for over 25 years, building business and Web applications since the very early days of the Web when you needed a hand crank (or a pair of wire splicers) to get online. Today Rick builds client-centric Web applications and services for customers with HTML5, JavaScript and mobile Web technologies, using AngularJS on the front end, and the ASP.NET stack and Microsoft technologies on the back end. Rick's company, West Wind Technologies, also produces a number of developer-related tools, including West Wind WebSurge, West Wind Web Monitor, and Html Help Builder.  Rick also maintains a host of open source libraries at github.com/RickStrahl and you can find his blog at weblog.west-wind.com  or contact him directly at rstrahl@west-wind.com.