Tag Archives: EF

Updating to RC2: Changes to EFCore, ASPNETCore, PostgreSQL driver & XUnit

Here’s my EFCore RC2 Demo on Github

The long-awaited 2nd release candidate came out earlier this week (here is the team’s announcement: Announcing ASP.NET Core RC2).

I have been sticking with RC1 and avoiding mucking with the nightly builds as Microsoft evolved this stack towards RC2 because so much was changing. Others were braver such as Shawn Wildermuth, the beardy Shane Boyer and the sad people who have been building products and tools dependent on ASPNET Core.

So as soon as the new bits were released I sat down to finally update the sample application I’ve been using at conferences since March that were still on RC1. Although it’s all cross-platform, I’ve been working on this sample on my MacBook directly in OSX and using only the CoreCLR just to prove to myself that this stuff is truly cross-platform. I’ve even set Mono aside.

I had two tiers of problems to attack: first getting the new CoreCLR (and the CLI that gives us dotnet commands, replacing dnx, dnvm and dnu) onto my Macbook, second was updating my sample which was dependent on a variety of technologies and APIs.

I’ve pushed the updated version of the application to github and renamed it: https://github.com/julielerman/EFCore-RC2-Demo. But I want to share some of the things I did to get this all working. Shawn wrote a great post on updating his app and the aspnet documentation has a doc on updating from RC1 to RC2 as well. I would start with these. I will focus on some of the changes I had to make that either aren’t covered in those posts, aren’t as obvious or just gave me extra heartache.

I would definitely recommend looking at my repository though since it does have working code so if you’re stuck on something and it happens to be something I already did, you might find an example to borrow within my app.

Getting the RC2 CLI onto My MacBook
For most, it should be easy. Just follow the instructions on Microsoft’s .NET Core page (there are different pages for different platforms).

It seemed to work. But I quickly ran into some problems when I was tryingi to convert my code and those led me to a few threads that said I may not have the correct version. There is some question about how much needs to be removed from your system so that you don’t have leftover older bits of CoreCLR hanging around causing conflicts. In fact, a key element of the update is to run an uninstall script (on the instruction page linked to above). There was a pull request to update that script to do a better job of cleaning the old version out before installing the new version. (Since then that PR has been modified and merged and is now what you will get from the instruction page.)

I grabbed the existing pull request version of the script and ran it then re-ran the installer. So began a bunch of lost and frustrating hours because suddently the dotnet command was gone. I kept getting “dotnet command not found” errors. (See next section about that). Keep in mind that I’m still fairly new to OSX so some of my lost time was due to things like being told to go to the “usr” path and my windows brain translating that to users/julielerman. I made the mistake of going to the latter. That wasted a lot of time. But I eventually got it sorted out.

Because I did not have a straight path to success, it is difficult to say what exactly was wrong and what was right. Hopefully the new uninstall script will do the trick. If not I suggest looking at ideas in this thread: dotnet command can’t be found on osx with RC2 bits

Dotnet command not found on OSX?
There are two important takeaways in solving the problem of dotnet not showing up on OSX.
1) For those using zsh as the default commandline instead of bash:
“There is an issue in the way path_helper is working with zsh on OSX. The easiest way for you to get unblocked is to simply symlink the dotnet binary to /usr/local/bin using the following:
ln -s /usr/local/share/dotnet/dotnet /usr/local/bin

This may eventually not be necessary. See this issue for a conversation about making the uninstaller smarter on zsh.

2) Problem with dotnet command on bash
Another user had the same problem but on bash so the symlink was not the answer. Eventually he discovered that some app had installed the following into his ~.bash_profile file:
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Applications/GitHub.app/Contents/Resources/git/bin:/Applications/GitHub.app/Contents/Resources/git/libexec/git-core
He removed it completely and got success although Zlatko K (from the cli team) made this suggestion:

You can actually keep that and just have the following:

export PATH=$PATH:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Applications/GitHub.app/Contents/Resources/git/bin:/Applications/GitHub.app/Contents/Resources/git/libexec/git-core
I don’t know who did that to your .bash_profile but that is the reason why it is happening. And yes, they should not be doing this. They should be adding your path as well.

Updating Visual Studio Code and (yippee) Debugging!

Since I’m doing this on a mac, I don’t have all the benefits of Visual Studio, but Visual Studio Code is pretty awesome. And with it’s limitations, it really forces me to learn my lessons more deeply & memorably, whereas with VS, I can get away with more thanks to all of the extra support. If I was on my regular computers (read: Windows) I would absolutely be using VS, not VSCode). So doing all of this on the Mac gives me some advantages in having to comprehend everythnig I do more clearly. And, it’s fun using the Mac after only using Windows for so long. But I’m not trying to tell anyone they should do all of their .NET coding on a Mac.

So with that out of the way … 🙂  With RC1, VS Code did not have debugging support. So I had to let errors happen and then read the stack output to figure out what was wrong. Again, much harder, but good lessons for me. 🙂 But please do be sure to update VS Code and the C# extension to their latest versions. VS Code will help you create a default launch.json file so that the debugger knows how to launch your app and a tasks.json for the defining the build task that’s specifed in the launch file.

This happens when you debug if there is no launch.json yet. Notice the box to the right of DEBUG and green arrow. It says “<none> ” since no launch file was found. I’m being prompted to create a new one and to select from either Node.js, VS Code EXtension Dev, .NET Core or Chrome. .NET Core is the one you want.

It will create and display the new file in the edit window.

There is one change you need to make to the default which is to point to the dll of your app that gets built by build. I failed at that because I had not noticed a left-over angle bracket from the place holder. 

Here is the original line that you get with the placeholder:

"program": "${workspaceRoot}/bin/Debug/<target-framework>/<project-name.dll>",

The target framework is (currently) netcoreapp1.0. My project name is src because I’m a dope and never changed that folder name. So the dll is in the /src/bin/Debug/netcoreapp1.0/ folder. Therefore the new value is:

"program": "${workspaceRoot}/src/bin/Debug/netcoreapp1.0/src.dll",

Updating the Code

Once I had this sort out, it was time to modify my code. Again, I would start by following through Shawn’s and the teams posts (links above) about the obvious and not so obvious things to hit. This will get things like namespaces covered, an updated main method in startup etc. I will call out changes that were significant to me. But please do look at the commits and history of my github repository for more details.

Wiring up EF and ASPNET Core’s Services for Dependency Injection in Startup.cs

This code looks a lot different. We used to explicitly AddEntityFramework, then Add[dbprovider] then set up the context for injection providing options. Here is the old code

services.AddEntityFramework().AddNpgsql()
.AddDbContext
(options => options.UseNpgsql
(Configuration["Data:PostgreConnection:ConnectionString"]));

With the new code, you just add the DbContext and that signals the obvious dependency on EntityFramework. Similarly, the Use[dbprovider] method triggers the obvious dependency on the provider. Much more succinct. 

services.AddDbContext
(options =>options.UseNpgsql
(Configuration["Data:PostgreConnection:ConnectionString"]));


Changes in my DbContext Class 

I was using an overloaded constructor of DbContext that allowed me to pass in an ASPNetCore service provider. This was to enable a fancy way of letting my integration tests leverage the IoC  services and the dependency injection. The DbContext overload that took in a servicePRovider has disappeared because there is a better way.

So I deleted that constructor of my weathercontext class.

I have some hack code in my context class to ensure that my database table names are “pluralized” since that does not exist yet in EFCore. I read somewhere about at least making the table names align with DbSet names but a) I didn’t see that kick in yet and b) I typically don’t create DbSets for every entity that maps to a database table. So I’ve left the hack code in. You can see it in the WeatherContext class. It just iterates through the entities known by the context and specifies that the relevant talbe should have the name of the entity plus an “s” . I got that from a gist shared by Rowan Miller (EF program manager).

Use of ServiceProvider in an Integration Test

More interestingly, the changes to how to user the service provider allowed for cleaner code in my test class. Note that I have two version of the test class. One is simple where I instantiate the context directly and pass in options specifying to use the InMemory provider. The other is built to take advantage of aspnet core’s IoC/DI services. That’s the one that I’m changing.

Originally in that test class’ constructor I had to create a servicecollection (that ties back to aspnet core services) and to that, specify that I want to use EF and the InMemory database. This is similar to the original code in Startup that I changed above.

_serviceCollection = new ServiceCollection();
_serviceCollection.AddEntityFramework().AddInMemoryDatabase();

The change to this code is similar to the change I made in the startup file:
_services = new ServiceCollection();
_services.AddDbContext(options => options.UseInMemoryDatabase());

(Note that I changed the variable name to _services)

Next in the setup code where I create the context instance and populate it, I was using the services to create a ServiceProvider and passing that into the WeatherContext constructor. That is how the context got the info about the database. I copied this code from the MusicStore sample and am now scratching my head about it because I’m still instantiating the WeatherContext and I still have that options parameter. So it makes no sense. Nevertheless, that code is gone and I’m now using the _services to do their job :

var serviceProvider = _services.BuildServiceProvider();
var serviceScope = serviceProvider.GetRequiredService().CreateScope();
context = serviceScope.ServiceProvider.GetService();

The provider will now to instantiate the context for me and the _services is aware of the InMemory provider. I wonder if I could have written it that way before. But thankfully the fact that the DbContext can no longer even take a ServiceProvider as a parameter so I got forced into the path of writing a better version of this code. 🙂

Speaking of Testing: Changes for xUnit APIs
My tests use xUnit. Brad Wilson and team have updated xUnit to work with RC2. This requires some changes to the project.json used in your test project. I looked at the documentation and focused my gaze on the dependencies section, missing an important detail just above it.

Please do look at the doc “Getting started with xUnit.net (.NET Core / ASP.NET Core)“. While all the info is there, let me just highlight the critical stuff, especially the one I overlooked!

The bit I overlooked is that there’s a new parameter called testRunner and it’s value is, surprise, xunit.

The names of the packages in dependencies are the same but their versions are updated. Here is what I had to change in my project.json for my test project:

"testRunner": "xunit",
"dependencies": {
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-build10015"
},

Equally important is to update the location of the nuget package. That goes in the new Nuget.config file where you list the package sources.

Here is the line in my Nuget.config that specifies the source where the RC2 version of the xunit packages live:

<add key="xunit" value="https://www.nuget.org/api/v2/" />

Updating Refs to PostgreSQL
When I’m in my app proper (as oppsed to tests), I’m using PostgreSQL. The RC2 package has a different name than RC1. And it, too, has moved to a stable package source.

In project.json I switched out:
“EntityFramework7.Npgsql”: “3.1.0-rc1-3”,

for
“Npgsql.EntityFrameworkCore.PostgreSQL”: “1.0.0-*”,

Note that Microsoft is asking all of the providers to follow this naming pattern using EntityFrameworkCore.

The package source has also moved to a stable location. Here is the relevant listing in my Nuget.config file:

<add key=”NuGet.org” value=”https://api.nuget.org/v3/index.json” />

I had to be sure to get rid of cached packages on my computer. Because I’d been trying and retrying things and not always doing it right, I found myself clearing out the cache where the package lists live on my computer (remember I’m on a mac)

~/.local/share/nuget/v3-cache/ then find the folder that contains the name of the source e.g. “****api.nuget.org.v3”.

Also I had to get rid of the actual packages. Those are in

~/.nuget/packages/[nameofpackage]

Again because I’m an OSX newbie, I’ll clarify that the “~” represents your home folder as a user. I wish I’d had help with this, but everyone presumes you know what that ~ means. Here’s my File system. MacintoshHD is my computer. I’ve done a trick to display the hidden files & folders .. those are the ones that are gray, not black. Ive drilled into Users, then me (julialerman). That’s ~. That’s the starting point. Antyhing after that is in the next column. You can see the .local folder where the . I’ve chopped it off in the screenshot but the .nuget folder is just below.

folders

That should help you be sure you’re getting the right packages.

Dont forget to keep restoring the packages. At some point (when I had more and more of the right things in place, e.g. the launch.json, etc), Visual Studio Code’s prompt to do a restore finally switched over to running the “dotnet restore” command instead of the old “dnu update”.  But for a while I was just running dotnet restore at the command line and you can see the difference between when it’s finding the right packages and when it’s not.

It’s a process

I should remind you that this did not happen in one smooth sitting. Working in the code I had to get the packages to restore without errors. Then I had to modify the code and build and look at the list of errors and then fix them and build again and fix an dbuild and fix and build and fix and build.

Once I got build down to 0 errors, then I could try to run. I was back and forth from running at the command line (dotnet run) and debugging in Visual Studio Code when I needed to really see step by step where an error was coming from.

The Controller Class

I didn’t really have to do anything to the controller class. I had stopped using the special EF change tracking parameter that the team was experimenting with (a parameter of Add/Update/Remove) because I knew it was going away.

I knew that a nice change to MVC in RC2 was that you don’t have to explicitly inherit from the Controller class if you are following one of the conventions that alert .NET that this is a controller class. So I removed it from WeatherController and ValuesController but then added it back in to the first since I didn’t feel like adding Dispose into the class. 🙂

Seeding Data

EFCore does not have a built in way to seed data yet like we’re used to with Code First. For RC1, I borrowed an example from the MusicStore sample for seeding data and modified it to suit my needs. That’s the SeedData class in my repository. This class is called by the web api’s startup and takes advantage of the asp.net services (the IoC stuff) so I can interact with EF and save the seed data into the database. I had to modify my RC1 version to align with the changes I’ve talked about already with respect to how to work with the context “out of band”. So the changes I made here are similar to the changes that I made in the controller class that I mentioned above.  Essentially, I have it use the SErviceProvider to instantiate the WeatherContext for me using the defaults already defined in startup.  Since I showed that change above for the test class, I won’t bother repeating it here. Because this sample is a demo, I use EF’s EnsureDatabaseDeleted and EnsureDatabaseCreated in the seed class to drop and recreate (and reseed) the database every time I run the app.

EF Migrations

My demo also uses migrations so I had to get all of that working again as well. Most of that change is related to the project.json file.

Up through RC1, the migrations commands were found in the EntityFramework.Commands package. Additionally every provider came with a second package with the name .Design appended to it, that you needed to have in order to use the EF commands.

So my RC1 project.json for the app (not the tests) had these in the dependencies:

"EntityFramework7.Npgsql": "3.1.0-rc1-3",
"EntityFramework7.Npgsql.Design": "3.1.0-rc1-5",
"EntityFramework.Commands": "7.0.0-rc1-final",

EntityFramework commands have been wrapped into what is now considered the tooling for CoreCLR.  So it’s package has the name tools now and also all of the tooling is in a different path to being ready. Their verson indicates that. This is the new package name alongside the new package for Postgres that I showed before:

"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-*",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview1-final",

Notice that the Design package is not there. I forgot to add it in and my migrations worked so it turns out that they may not be needed (at least not for what I’ve done so far with migrations).  That was even a surprise to Shay Rojansky who has built the provider. 🙂

However there is another important piece to getting migratons to work and its a big change to project.json. There is a new tools section you must add.  The Kestrel server for IIS integration also has to be added into tools so I’ll show you the entire tools section from my project.json file:

"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": {
"version": "1.0.0-preview1-final",
"imports": "portable-net45+win8+dnxcore50"
},
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview1-final",
"imports": [
"portable-net45+win8+dnxcore50",
"portable-net45+win8"
]
}
}

In RC1, we also added in shortcuts for the commands. To use the kestrel server, we could type dnx web at the command line and “web” was a shortcut for the IISIntegration. To use migrations we started with “dnx ef”. EF was a shortcut to the EntityFramework.Commands assembly. Commands no longer exist. Instead we list the tools. But how do we specify the shortcuts? Yes I was wondering. Well for entity framework, its built in. I was able to type “dotnet ef” and get the happy little magic unicorn along with the listing of the commands available for ef migrations.

dotnetef

I’ve written an extensive article on the new migrations commands for EFCore if you want to learn about the commands. That article also includes the powershell versions of the commands that you may be familiar with in Windows e.g. add-migration.

There were more changes, but none that stand out in my memory as much as these. You can see the working code in my repository and look through its history to see how its evolved. Unfortunately isn’t just one commit that brought me from RC1 to RC2 so you may need to look at a few bits of historical commits to see the old vs new code.

 

EF7 is now EF Core 1.0, Package and namespaces change too

The big news last week was that the ASP.NET 5 & EF7 stacks were renamed in an attempt to alleviate the confusion around the naming of everything under the ASP.NET 5 umbrella.

ASP.NET 5 is now ASP.NET Core 1.0

EF7 is now EF Core 1.0

The naming has been a topic of debate since each of these were introduced by Microsoft and throughout their development. The teams finally accepted that the myriad questions and complicated answers about the naming in the ASP.NET 5 stack was enough of a red flag to change the names. While it is a huge relief to many, the timing is problem for people who have invested in asp.net 5 already because the name is not just a brand but it will affect packages as well. As per the announcement on github

  1. The Microsoft.AspNet.* packages and namespaces are changing to Microsoft.AspNetCore.*.
  2. The EntityFramework.* packages and namespaces are changing to Microsoft.EntityFrameworkCore.*.
  3. The version numbers of all of the above are being reset to 1.0.0-*.

Changing the namespaces this late in the game is going to be painful for devs/companies who have already been building apps and tooling on ASP.NET 5 &/or EF7. We are already on RC1 which was released in November with a go live license. Rick Strahl has a great [balanced] post talking about this.

Other than this, both ASP.NET Core & EF Core will move forward as planned. RC2 is supposed to be out sometime in February and they remain committed to the initial RTM at the end of March.

Here are the new namespace names for EF Core for RC2, as per https://github.com/aspnet/EntityFramework/tree/dev/src


In EF7 In EF Core
EntityFramework.Core Microsoft.EntityFrameworkCore
EntityFramework.Commands Microsoft.EntityFrameworkCore.Commands
EntityFramework.MicrosoftSqlServer Microsoft.EntityFrameworkCore.SqlServer
EntityFramework.MicrosoftSqlServer.Design Microsoft.EntityFrameworkCore.SqlServer.Design
EntityFramework.Relational Microsoft.EntityFrameworkCore.Relational
EntityFramework.Relational.Design Microsoft.EntityFrameworkCore.Relational.Design
EntityFramework.InMemory Microsoft.EntityFrameworkCore.InMemory
EntityFramework.Sqlite Microsoft.EntityFrameworkCore.Sqlite
EntityFramework.Sqlite.Design Microsoft.EntityFrameworkCore.Sqlite.Design

If you are curious about what’s in EF Core, check out my EF7 Course on Pluralsight which I created during the Beta 4 …then read my recent post, EF7 Updates and Changes on Pluralsight’s blog which takes you from there to the current RC1.

Getting Started with EF6 Course on Pluralsight

image

You may think you read that title wrong. Does she mean EF7? No, I actually invested some time into creating a new Getting Started with EF6 course even though EF6 was released about 18 months ago. When EF6 was released, most of what changed since EF5 was the advanced features and usage. I did a course called “EF6 Ninja Edition: What’s New in Entity Framework 6” specifically to cover those additions/improvements. But for the “toes in the water” first look at EF, not much had changed between EF5 and EF6 so the Getting Started with EF5 course remained pretty relevant.

Watch Getting Started with Entity Framework 6

So why Getting Started with EF6 now, when EF7 seems to be around the corner? Well, EF7 is still going to be a while. Even though a “Beta 6” was announced recently, the team has said in a significant way that EF7 Beta 6 is still “very much a preview” of EF7. A pre-release of EF7 is expected in early 2016 along with the release of ASPNET5. But the RTM of EF7 is still further off than that date. And even then, not everyone will be using EF7 right away.

So EF6 will be around for a long time and I decided that it was useful to have a course that addressed Getting Started with EF6 directly including using the latest version of Visual Studio – VS2015.

The first module is an overview which is designed for not just developers but even your managers who may want to have a better understanding of what EF is and how it fits into your overall plans.

I am also committed to creating two more EF6 courses for Pluralsight — also for the sake of being long-term resources. These will consolidate information in the various courses I’ve created about EF3.5 – 6 over the years. One will be an EF6 Fundamentals and the other will be Advanced EF6.

In the meantime, I’ll be updating the “Looking Ahead to EF7” course to reflect the Beta 6 since things have evolved since Beta 3 when I did that course.

Installing EF Power Tools into VS2015 (with an update for VS2019)

March 2020: In comments below, someone asked about VS2019.

The EF Power Tools Community Edition (see July 2017 note below) still works for VS2019.

Erik EJ also created EF Core Power Tools.

While I’m at it, I thought I would also point out the plain old EF Tools for VS2019. For VS2019 (& IIRC for VS2017), these tools are installed via the Visual Studio Installer.
Entity Framework tools are installed as part of the Data storage and processing workload in the Visual Studio Installer.

You can also install them as an individual component under the SDKs, libraries, and frameworks category.

July 2017: something amazing happened! Erik Ejlskov Jensen, the creator of the SQLCe provider Entity Frameworkas well as the creator of the very popular SQL Server Compact Toolbox extension for Visual Studio, has given us a community version of EF Power Tools for VS2015 and VS2017. Thanks to the tools already being on GitHub, he forked the tools and now we have

EF6 Power Tools Community Edition that you can get via Visual Studio Extensions

Oct 2016 note: There have been over 60,000 hits to this blog post so far. My host is reaping the benefits ($$$). In July, I submitted a pull request to update the VSIX. The PR was finally merged. Now just waiting for the change to show up in the VS Gallery.

TLDR: If you don’t want to do the tasks (even though they are so easy) you can download the updated VSIX I created from here.

The Entity Framework Power Tools extension for Visual Studio has been around for quite some time and is still called a Beta. I cannot live without it’s “View Entity Data Model (Read-Only)” feature which I used to validate my code first models.

But if you try to install the extension into Visual Studio 2015, you won’t find it.

7-25-2015 9-47-12 AM

Checking the extension in Visual Studio Gallery, you’ll see that it hasn’t been updated to install into VS2015.7-25-2015 9-47-49 AM

The fix is nothing more than making it know about VS2015. There are no other compatibility problems that I have experienced. Modifying an extensions installation package (which is just a zip file!) to be aware of another version of Visual Studio is pretty easy. Here are the steps to get the EF Power Tools into VS2015.

Download the extension from the Visual Studio Gallery page.

Find the file

7-25-2015 9-50-13 AM

and change it’s extension to zip.

7-25-2015 9-50-33 AM

Extract the files from the zip file.

7-25-2015 9-53-01 AM

Open the extension.vsixmanifest file in a text editor and find the Supported Products section.

7-25-2015 9-53-25 AM

And copy paste one of the Visual studio elements, changing the version to 14.0. I have the Enterprise version but didn’t bother changing it from Pro here and it didn’t seem to be a problem.

7-25-2015 9-53-47 AM

Now you have to reverse your steps in order to recreate the VSIX file.

Select the files in the extracted folder and zip them. Don’t zip the folder. The files have to be at the root. (Guess how I learned that! Smile ) I named my zip file VSPowerTools15.zip

7-25-2015-9-55-47-AM.png

Rename the file to have the vsix extension.

7-25-2015 9-56-01 AM

Run the file right from here.

7-25-2015 9-56-16 AM

Voila!

7-25-2015 9-56-22 AM

If Visual Studio was open, you’ll have to restart to get this to kick in.

Also you’ll see Entity Framework Power Tools listed in the installed extensions when you look at the About section of Visual Studio 2015.

I accidentally mistook this for something it was NOT and (embarrassingly) tweeted it. I had forgotten that I had done this for the VS2015 preview. Then I installed VS2015 RTM on top of the preview and that picked up all of the installed extensions. When I saw the power tools listed in About, I thought they had a) finally gotten rid of the “Beta” tag and b) installed automatically with VS2015. When I realized the extension was installed, I uninstalled that and indeed the tool went away. So for anyone who saw that tweet…. sorry! Guilty as charged …

Looking Ahead to Entity Framework 7 on Pluralsight

Pluralsight has published my latest course, a 2.5 hour course about Entity Framework 7 (EF7).

“Looking Ahead to Entity Framework 7”

EF7 is not released yet. It will get released as a “pre-release” along with ASP.NET 5 so that there is a data stack available for projects that target the CoreCLR. Then the team will do a lot more work on EF7 for a full release possibly (wild guess) at the end of 2015. There are a lot of changes since EF7 is begin rewritten from the ground up. Many new features – from things like Batch Updates that we’ve been asking for since v1 to totally new concepts like being able to query and update against non-relational data stores. But there will also be things that do not get carried forward – most notably for some is the EDMX, the designer based entity model.

This course will show you what’s coming, what’s going, demonstrate a lot of the new features (as they are currently …aka the Alpha or earlier versions) and provide guidance about deciding if and when to move to EF7.

Here is an list of the modules:

You can see the more detailed Table of Contents here.

I’ve already gotten some great feedback on the course. My favorite tweet so far was:

“Great info and insight. I don’t know if I’m happier with what’s being added or being removed.”

Check it out and let me know what you think of EF7!

Some Observations While Playing With EF7 Alpha Bits: Current vs On-Hold APIs

You may or may not have caught this important blog post from the EF team about plans for the first RTM of EF7:  EF7 – Priorities, Focus, and Initial Release. In it, EF Program Manager, Rowan Miller explains that for its initial release, EF7 will target ASP.NET 5, ensuring that ASP.NET 5 has a solid data platform to release with. It also means setting aside some of the proof of concept work that the team has been working on for it’s “new platforms, new data stores” initiative. Namely, Windows Store &  Windows Phone and the non-relational providers that the team has been experimenting with are on hold until after the initial RTM of EF7. This does *not* mean that they are being dropped, just delayed so that the team can focus on shipping something usable sooner. Rowan is also clear about the fact that EF7 will not be considered the “go-to” EF version until much later when they’ve brought these other features in as well as forged ahead with more parity with EF6. I recommend that you read that post.

So what does that mean with respect to the source code for EF7 on Github and the current preview Nuget packages of EF?

Note that I have a package source that is pointed to the ASPNET vNext packages which is also where EF7 lives on myget: https://www.myget.org/F/aspnetvnext/api/v2

Also that I have selected PRERELEASE packages:

image

And using the console, that means always adding the “-pre” parameter after the install-package command (e.g. install-package entityframework –pre).

First, here’s a look at what DLLs were on Nuget prior to the shift

image

The shift occurred when the nuget packages went from being tagged as alpha to being tagged as RC. Note that these nuget tags do not reflect the state of EF7, but a package naming decision.

image

Notice that the AzureTableStorage, Redis and SQLite packages are still there but they are from Dec 1, 2014.

Notice the addition of EntityFramework.Core. That’s where all of the core bits are now.  But the entityframework package is still there. You still start by installing entityframework.

The entityframework package has a dependency on entityframework commands and will pull that in and then that forces nuget to also pull in entityframework.core, relational and migrations. You’ll need to explicitly install entityframework.SqlServer or InMemory if you want them. You’ll need at least one of those.

When you install EF7 from the ASPNetVNext package source, when the installation is finished the following HTML page will pop up in Visual Studio:

image

I have not tried to use the older providers. They are not going to be kept in sync with the moving forward packages. They will get caught up after EF7 has its initial release.

Also, you do have the ability to get at the source code as it was prior to this big shift. Check the “futures” branch on github:

https://github.com/aspnet/EntityFramework/tree/futures

I believe this is a snapshot that was taken prior to the shift.

Unfortunately, it’s not possible to keep all previous versions of packages on MyGet the way it is on Nuget.  You can get a snapshot of the beta2.11514 packages that Rowan Miller set aside for his Connect demos. https://github.com/rowanmiller/Demo-EF7/  That’s not the latest version of EF7 prior to the shift but close.

Just remember, it is all still early early, evolving and changing rapidly.

Some Observations While Playing With EF7 Alpha Bits: EF7-Able Projects

You can’t install EF7 into just any project. Especially now that they are making the shift to focusing on ASP.NET 5 for it’s initial release.

Here are combinations that will work:

(Have not tried VS2012 ..)

Visual Studio 2013

.NET 4.5.1 projects only

Class Library, Client Projects (WPF, Console, Windows Forms), ASP.NET Projects, WCF

Later in 2015, EF7 will return to working with Windows Phone/Store, but for now, none of the relevant projects will host EF7 (e.g. universal apps, PCLs, etc)

Visual Studio 2015

.NET 4.5.1+ projects only

Class Library, Client Projects (WPF, Console, Windows Forms), ASP.NET Projects, WCF

ASP.NET 5 vNext Console & Class Library projects (and yes, the first sounds like an oxymoron)

image

ASP.NET apps (and if you’re looking for vNext, those are in the templates)

image

Some Observations While Playing With EF7 Alpha Bits

My first coding foray into EF7 was as a code monkey for Pranav  Rastogi from the ASP.NET team at TechEd Europe where he walked me through converting a simple EF6 app to EF7. (“Entity Framework Now and Later”, my bit starts at about 50 minutes in.) My next EF7 playtime was working through demos created by Rowan Miller (program manager on EF team) that are available here on his github account: https://github.com/rowanmiller/Demo-EF7/.

These demos depend on a snapshot in time of EF7 alpha  (EntityFramework.7.0.0-beta2-11514)  and demonstrate using EF7  & SQLite in a Windows Phone and Windows Store app as well as against a non-relational database (in this case Azure Table Storage). It also demos some other new features like batched updates, improved LINQ queries and more.

I used these same demos for a conference presentation which meant I practiced them repeatedly and modified them a bit to make sure it flowed in the way I preferred.

The bits are evolving rapidly. I’ve since been reading and writing about EF7 and played just a little but now I’m starting to have my most fun which is asking myself “what happens if I do X? what happens if I do Y?”, debugging, comparing and contrasting behaviors.

With the caveat that EF7 is still alpha and things are still evolving and shifting, I wanted to share some observations as I am playing with it.

1) InMemoryStore Before Committing to a Data Store

When you do any interaction with the DbContext even if you are not trying to query or save data, EF7 still wants you to specify the data provider in DbContext configuration.  Since I’m not yet interested in actually hitting a database, the new InMemory provider is the perfect foil!

In DbContext, I can install the entityframework.InMemory package then specify in my DbContext class that this is the provider I want to use and then I’m good to go.

protected override void OnConfiguring(DbContextOptions options)
{
  options.UseInMemoryStore();
  base.OnConfiguring(options);
}

I’d used InMemory for unit tests already but I was just using a simple console app to fiddle around EF7 with. That’s still testing, and that’s what the InMemory provider is for – testing.

What I’d like to do is be able to switch the context on-the-fly to use in memory store so I can have a single defined context with all of it’s dbsets, mappings etc and switch it easily to use my real data store or the InMemory store. So in a test project, I’d be able to say “use the context, but for these tests, use the InMemory store”. I see notes on github that this is a goal – e.g. specify provider along with connection string in a configuration file.

Rather than an enormous blog post, I’ll just publish this first bit and add more in bits and pieces …kinda how EF7 is being built anyway. Smile

EF6 Ninja Edition Course is Live on Pluralsight

It’s been a long haul and a long wait. I started work on this course, then switched gears to work on the Domain–Driven Design Fundamentals course with Steve Smith. When I returned to work on the EF6 course, a number of minor releases and patch releases had been published so I had to revise much of what I had already recorded, edited and produced.

But today, finally, the full course has been published on Pluralsight.

Entity Framework 6: Ninja Edition
– What’s New in EF6

It is a little over 7 hours long. This is what I would have done had I written another huge book. So if you are looking for my next book, just watch this course! And you can go back to it for reference.

If you don’t have a Pluralsight subscription (and honestly, the $29 monthly fee if you were to just subscribe to watch this course, is less than those huge books), send me a note and I’ll send you a code for a trial. You’ll probably realize quickly that you want a subscription though to continue accessing the enormous library.

Course Description

Entity Framework 6 brings major improvements to EF that allow developers to align their data access with advanced software practices. The biggest news for EF6 is that it is open-source and has gained a lot from developer community input. Features with broad appeal such as stored procedure mapping in code first, support for the Async/Await pattern when executing queries and commands, simpler patterns for unit testing, and built-in database logging capabilities have gotten a lot of visibility. EF6 is now very extensible with custom Migrations, custom mapping conventions, and the introduction of Dependency Injection patterns to open up low-level DbContext configuration. There are new methods and properties that allow simpler and smarter coding patterns. Rather than present a high level list of the new features, this course dives into each new feature in EF6, ensures that you understand not only what it is for, but how it works, scenarios where you can benefit from it, and gotchas you should watch out for. This course provides a comprehensive look at what EF6 adds to Entity Framework, and it will leave you with the ability to truly benefit from all of the Ninja power that’s been added to this version of EF.

Course Outline

Overview of What’s New in EF6

Introduction

What Is Entity Framework?

What’s in This Course?

What’s in This Module?

A Brief History of Entity Framework

Why EF6?

A Lap Around EF’s CodePlex Site

Overview of Changes to the EF Designer

Overview of New Features

What’s Not (Yet) in EF6

Summary

Resources

Getting to EF6

Introduction

In This Module

Getting EF6 Into New and Old Projects

Updating Projects to EF6

Summary

Resources

Performance and Stability Improvements

Introduction

In This Module

Faster Processing of LINQ’s Enumerable Contains

Faster Mapping View Generation

Using nGen to ‘Pre-JIT’ EF6 Assembly

Reuse Open Database Connections

Create DBs That Are More Scalable and Less Prone to Deadlocks

Connection Resiliency for Transient Database Connections

Digging into the Connection Resiliency Feature

Quick Review

Resources

Changes to the EF Tooling

Introduction

EF Designer History

In This Module

EF Designer’s New MSI Installer

Creating a Code First Model From a Database in the Designer

Database Views in Your Code First Model

Customizing the Code First Designer Templates

Refactoring the Generated POCOs and Model

A Warning About a Naming Conflict With Code First From Database

What Does the Empty Code First Model Wizard Do?

Comparing the Code First Model Wizard to the EF Power Tools

Using EF4 or EF5 With the New Designer

A Notable Change to the Model First Workflow

Why You Still Need the EF Power Tools

Quick Review

Resources

Stored Procedure Mappings for Code First

Introduction

In This Module

Understanding EF Stored Procedure Mappings

Visualizing Stored Procedure Mappings

Differences Between Designer-Based and Code First Model Mappings

Conventions for Procedures Created by Code First

Customizing Mappings to Work With Existing Stored Procedures

Quick Review

Resources

Custom Code First Conventions

Introduction

In This Module

Custom Code First Conventions: Why Would You Want Them?

Custom Conventions Basics With Lightweight Conventions

Using Attributes to Specify Custom Conventions

Encapsulating Custom Conventions

Understanding and Controlling Execution Order

Model-Based Conventions

Extending Existing Conventions

Quick Review

Resources

More Code First Goodies

Introduction

In This Module

Database Index Support in Code First

Adding Indexes With Fluent API

Setting the Default Database Schema

Using AddFromAssembly to Load Conventions and Configurations

Understanding and Fixing How Code First Pluralizes Table Names

Using a PluralizationService to Localize Non-English Table Names

Implementing a Custom Pluralization Rule in Your Data Layer

Mapping to Results of Table Value Functions and Stored Procedures

Quick Review

Resources

Enhancements to Code First Migrations

Introduction

In This Module

Affecting the Schema of the Migrations History Table

Smarter Migrations With Idempotent Scripts

Limitations of Existing Migrations Methods

How Migrations Get From Method to SQL

Create Custom Migrations for Other Database Operations

Why HasColumnAnnotation and HasTableAnnotation?

Implementing a Simple Table Annotation

Implementing More Complicated Annotations

Performance Tweak for MigrateDatabaseToLatestVersion Initializer

Migrate From Multiple Models to a Single Database

Using HasDefaultSchema and ContextKey for Multiple Model Support

Easier Migrations for Multiple Models in a Single Project

Combining Database Initializers and Migrations

Quick Review

Resources

Improved Database Interaction

Introduction

In This Module

Simple Database Logging With the Log Property

Tweaking the Log Functionality

SQLCE Functions for LINQ Queries

Introducing the Async EF6 Methods

Demonstrating the Effect of Asynchronous EF6 Methods

Perception and Performance: Load Testing With Async EF6

Quick Review

Resources

Code-Based DbContext Configurations and Interceptors

Introduction

Why DbConfiguration?

In This Module

Creating and Triggering a DbConfiguration Class

Why Move Config File Settings to Code?

Moving Connection Factory to DbConfiguration

Moving Database Initializers to DbConfiguration

The New NullDatabaseIntializer

Provider Services and DbConfiguration

Tap into the Pipeline With Interceptors

Beyond the Interceptor Basics

What Stops Does the DbCommandInterceptor Make in the Pipeline?

Building an Interceptor for Database Logging

Using Interceptors to Solve Complex Problems

Understanding the Role of Dependency Resolution

Hosting DbConfiguration in External Assemblies

Quick Review

Resources

Sometimes It’s the Little Things

Introduction

In This Module

EF6 and Mocking Frameworks

Writing Tests to Mock Methods Like DbSet.Find

Writing Tests to Mock LINQ Queries

Nested Entities and Complex Types

Fixing the Ambiguous Types Problem

Custom Equals vs. Change Tracker Equals

Smarter LINQ to Entities Queries

Yes, You Can Haz Changes With HasChanges

Quick Review

Resources