# Some DDD+EF Resources

Could not fit this into a tweet in response to a request.

Here are some resources for how EF can be a partner to a Domain Driven Design world:

Update June 2015:

Microsoft Ignite, Chicago May 2015
Domain-Driven Design for the Database Driven Mind (90 minute presentation video on Channel 9)

Update: October 2014:

MSDN Mag Oct 2014 Issue:
Data Points: A Pattern for Sharing Data Across Domain-Driven Design Bounded Contexts
Julie Lerman explores a way to mirror data as one scenario for sharing data across DDD bounded contexts.

MSDN Mag Dec 2014 Issue:
Data Points: A Pattern for Sharing Data Across Domain-Driven Design Bounded Contexts : Part 2

Video: Oredev, Fall 2013 (by me)
ENTITY FRAMEWORK IN CORE-BUSINESS APPLICATIONS THAT LEVERAGE DDD

Video: TechEd North America, May 2014 (Vaughn Vernon)
How You Can Implement Aggregates and Domain Entities Effectively in Domain Models, with .NET

Article Series:
MSDN Magazine Data Points Column (by me) Aug, Sept & Oct 2013
Coding for Domain-Driven Design: Tips for Data-Focused Devs, Part 1
Coding for Domain-Driven Design: Tips for Data-Focused Devs, Part 2
Coding for Domain-Driven Design: Tips for Data-Focused Devs, Part 3

Domain modeling with Entity Framework Scorecard (Jimmy Bogard)

Bonus for NHibernate Converts:
And for those who are looking for this by way of moving from DDD + NH, Jimmy Bogard did a great post (with pointers to related posts) on Migrating from NHibernate to EF.

# Entity Framework, TimeSpan & SQL Server Time

In the “hey, you cant know everything” category….

A client asked me a question today about mapping TimeSpan to the Time data type in SQL Server.

I didn’t know there was a Time data type in SQL Server. I’m well aware of the Date data type we got in SS2008, but I skipped right past that other new type.

Since I never worked with a Time data type, I never had occasion to use it with EF. So when my client said something about timespan, I thought “that can’t be right”. Timespan is about intervals, not a point in time. Then he said something about the DateTime.TimeOfDay property which returns a timespan and I was all

So….

step 1:create a table in a SQL Server Database that has a Date field and a Time field.

step 2: reverse engineer to code first (I used the EF6 designer)

  public partial class SeparatedDateTime
{
public int Id { get; set; }

[StringLength(50)]
public string somestring { get; set; }

[Column(TypeName = "date")]
public DateTime justDate { get; set; }

public TimeSpan justTime { get; set; }
}
ok so there it is: TimeSpan
step 3: write some code to test it out:
    private static void InsertSeparatedDateTime() {

using (var context = new DateTimeTester()) {
context.Database.Log = Console.WriteLine;
context.SaveChanges();
}
}

private static SeparatedDateTime CreateSepDT() {
var sepDT = new SeparatedDateTime();
sepDT.somestring = "A Test";
sepDT.justDate = DateTime.Now.Date;
sepDT.justTime = DateTime.Now.TimeOfDay;
return sepDT;
}
step 4: debug.
check sepDT.justTime value and it looks like this : it is the milliseconds since midnight in many flavors
The log shows me that EF has transformed that value into a time value for the insert:
And surely it does the opposite when reading that data back out of the database.
Some caveats:
• 24 hr time only
• Presumes you calculated that timespan value correctly
• All caveats associated with UTC






# Recent Data Points Columns: Aurelia, Azure DocumentDB, Scriptcs, EF6, EF7, ASP.NET 5

#### Data Points – Aurelia Meets DocumentDB: A Matchmaker’s Journey (Part 1)

*Part 2 will be in Dec 2015 issue

Nov 2015

After exploring both DocumentDB and the new Aurelia framework, Julie Lerman decided it was time to use them together, but that proved more difficult than expected. Learn how she finally found the path to the correct solution.

#### Data Points – Revisiting JavaScript Data Binding — Now with Aurelia

Sep 2015

Julie Lerman has long been a fan of the Knockout JavaScript framework and its data binding talents. Here she explores the new Aurelia framework, which is quickly gaining momentum with Web developers, and finds that it offers a lot to like for data-oriented programmers.

#### Explore Entity Framework Behavior at the Command Line with Scriptcs

Jul 2015

Julie Lerman learns how to explore Entity Framework behavior interactively using Scriptcs.

#### An Overview of Microsoft Azure DocumentDB

Jun 2015

Julie Lerman takes a first look at the Microsoft entry into the document database field—Azure DocumentDB.

#### The EF6, EF7 and ASP.NET 5 Soup

May 2015

Julie Lerman discusses the difference between the next version of .NET and what ASP.NET 5 apps will run on, then explains how Entity Framework 6 and Entity Framework 7 fit into the mix.

#### EF6 Code First Migrations for Multiple Models

Apr 2015

The new support for Code First Migrations in Entity Framework 6 makes it easier to store data for multiple models in a single database. But that support may not be what you imagine. Julie Lerman explains what this feature does and doesn’t do, and how to use it.

#### Looking Ahead to Entity Framework 7

Jan 2015

In this first look at EF7, Julie Lerman discusses what EF7 will bring to developers, the motivations behind decisions being made about the framework, and what this version means to existing apps that use EF6 or earlier.

# EF7 EnsureCreated vs. Migrate Methods

I had a “demo gods” problem recently…of course I hit the jackpot combo during a conference presentation though never while practicing.

Remember that EF7 is not EF6 with new features. So behavior can change and I didn’t check this one.

In EF6 if you have migrations and either let DbInitialization create the database or use Database.Create(), the database will get created along with the migrations in the MigrationHistory table.

With EF7 if you use EnsureCreated to create the database at runtime, as I had in some of my tests where I literally wanted to check behavior in the database, the migration history table DOES NOT GET CREATED.

This messed me up because I was demoing a migrations feature after having run one of these tests. With the migration history table wiped out by my test, the update-database command attempted to start with the very first migration, not the one I had just added in my demo. This caused a conflict because that migration was attempting to create a table that already existed in the database.

I couldn’t figure out what the problem was on the fly, so I moved on, with assurances to the attendees that I’d done a lot of work with migrations and new they worked as expected. And that a) it was a beta b) I would run it by the team and c) “you can trust me”.

So, blaming it on “beta” was not fair and it was not right. The blame lay between the chair and the keyboard, as they say. I hadn’t even run that test in my conference session yet.  But I had re-run all fo the tests one last time right before I started the session, which put the database in this bad state.

Here, from one of EF7 issues raised on Github is Rowan Miller’s explanation:

EnsureCreated totally bypasses migrations and just creates the schema for you, you can’t mix this with migrations. EnsureCreated is designed for testing or rapid prototyping where you are ok with dropping and re-creating the database each time. If you are using migrations and want to have them automatically applied on app start, then you can use context.Database.Migrate() instead.

So I’ve gone back to my tests and made sure the ones that use the database make use of the Migrate command.

My anticipated uses:

• EnsureCreated for on the fly DB creation on devices (e.g. phones)
• EnsureCreated for integration testing when I’m pointing to a unique testing-only database.
• Migrate for integration testing when my tests involve a test database that uses migrations. I think this will be rare and this is what I wanted for my conference demo.
• Migrate for, as Rowan suggests, Migrating a db on app startup. This could be for example, client apps (ala WPF) or web sites you’ve deployed to Azure.

Keep in mind that these demos where Migrate made more sense, are demos I am using to help people understand how EF7 works, not to demonstrate how to build tests when employing Entity Framework in your application. So some of the things I am doing are not necessarily how I would use tests when building software.

# Diving Into ASP.NET 5 Beta 8? Don’t forget the web tools!

Some developers have been working closely with the evolving ASP.NET 5. Not me. I play with it once in a while. My last time was in the spring with the beta 4. Beta 8 was just released and I was working on creating a Web API. I had two projects in my solution. One was using the ASPNET5 Web API template from Visual Studio 2015.

The other used the ASP.NET 5 Class Library project template.

The Web API project had a reference to the class library project.

When I attempted to build the solution I got the following two errors that were coming from the Web API project:

CS1703  Multiple assemblies with equivalent identity have been imported: 'C:\Users\jlerm\.dnx\packages\System.Collections\4.0.10\ref\dotnet\System.Collections.dll' and 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Collections.dll'. Remove one of the duplicate references.
CS1703  Multiple assemblies with equivalent identity have been imported: 'C:\Users\jlerm\.dnx\packages\System.Threading\4.0.10\ref\dotnet\System.Threading.dll' and 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Threading.dll'. Remove one of the duplicate references.

I won’t bore you with everything I tried to sort this mess out. I finally did find a hack but then ran into another problem at run time — because of changes to web hosting — that was what eventually helped me find the solution to the first problem.

It turns out that the templates were my problem. There are some changes with beta 8 that resulted in the need for new project templates for Visual Studio 2015. They are contained in the ASP.NET and Web Tools 2015 (Beta 8) update for Visual Studio 2015.

# Visual Studio 2015, Command Prompt & Powershell ExecutionPolicy

Just a hint in case you run into this problem that took a few days to discover the pattern.

I have the Productivity Power Tools 2015 installed as an extension to VS2015. These are from Microsoft and there are a ton of features in there that I can’t live without.

With this I can right click on a solution or project in Solution Explorer and open a command prompt at the relevant path.

I mostly use this feature to get to posh-git to run some git commands.

posh-git is a PowerShell enhanced environment for the git command line.

There are plenty of other reasons you may want to use PowerShell interactively with Visual Studio. Working with ASPNET5 apps is a very good reason.

The problem I encountered was that occasionally, I would get into PowerShell but my Execution-Policy was, for some reason, Restricted, so I couldn’t trigger posh-git.

I finally figured out how to ensure I entered the command prompt with my normal Unrestricted ExecutionPolicy.

Be sure to open the Package Manager Console in Visual Studio first. That starts up Powershell with the correct policy. Then when you open your command prompt, you are good to go.

# Getting Started with EF6 Course on Pluralsight

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

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.

Checking the extension in Visual Studio Gallery, you’ll see that it hasn’t been updated to install into VS2015.

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.

Find the file

and change it’s extension to zip.

Extract the files from the zip file.

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

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.

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! ) I named my zip file VSPowerTools15.zip

Rename the file to have the vsix extension.

Run the file right from here.

Voila!

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 …

# EF7 Beta 4 & LINQ Queries: Be sure you have the right LINQ package

TLDR:
For EF7 Beta 4 (via nuget) the package you want is Remotion.Linq 2.0.0-alpha-002.

I recently updated some demos from using the EF7 stable (stable comes from Nuget.org, not the nightly build package source) version beta3 to beta4. It involved updating a lot of other packages and I know enough to be dangerous so this took me a while.

But I got it worked out and everything compiled and everything ran correctly …or so I thought.

There was a test I missed running which performed some LINQ queries.

I tried to demo that at in a conference session earlier this week at Techorama and it threw an exception. Rather than struggling with it, I assured the attendees that I knew this worked and was probably a versioning issue. I finally got a chance to dig into that today and have solved the problem.

It was indeed a version issue. I found a GitHub issue that indicated this problem was caused by having the wrong version of Remotion.Linq installed. But the conversation was based on an earlier build of EF7 and wasn’t sure which version of Remotion.Linq.

But in fixing the problem, I targeted the wrong version for an update, thinking the “stable” build might be what I wanted since the EF7 betas in nuget are considered “stable” betas. Unfortunately trying to install that stable version (1.15.15) caused nuget to hang for so long I had to just crash visual studio. I tried this repeatedly from different angles so I wasted over an hour being a dummy.

When I finally decided to try the 2.0.0-alpha-002 installed, it updated quickly and easily and my LINQ queries executed successfully.

# Some EF7 Beta3 to Beta4 API Syntax Changes

I am updating some demos I created earlier in the year and using the Beta4 version of EF7 that is the latest stable beta and available on Nuget as opposed to the super-bleeding edge APIs you can get via the nightly builds source.

There were some API changes to features I was using and I had to do a bit of exploring to sort them out so wanted to share in case you are doing the same.

Keep in mind that there are a LOT of things that have evolved between these two versions. I’m just focusing on the things I had to change so that my little demos continued to work properly.

AttachGraph

DbContext.ChangeTracker.AttachGraph is now DbContext.ChangeTracker.TrackGraph.

Here’s an example of it in use with a graph of all new objects and the root of the graph is newSamurai.

context.ChangeTracker.TrackGraph(newSamurai,


DbContextOptions

DbContextOptions is now DbContextOptionsBuilder.

You’ve most likely seen this used as a parameter in the OnConfiguring override for DbContext.

Here is the original signature:

protected override void OnConfiguring(DbContextOptions options) {}

Here is the new signature:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }

EF6 has DbSet.AddRange. Originally EF7 switched the functionality to be an overload of Add which was cool but not backwards compatible so we’re back to DbContext.AddRange and DbSet.AddRange.

DbContext.Entry.SetState( )

The DbContext ChangeTracker API since EF4.1 let us set state with

DbContext.Entry.State= EntityState (where EntityState is an enum)

EF7 started out with a nicer API for this which was

DbContext.Entry.SetState(EntityState)

But for the sake of backwards compatibility, it’s now back to

DbContext.Entry.State=EntityState

That’s what I’ve encountered so far. Hope it helps

# 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: