EF Code First Migrations, Update-Database outside of Visual Studio

In a recent blog post comment, someone asked “can you please tell them [EF Dev Team] some developers would like to use the Power Shell command script and not PM console to update database.”

If you look inside the package folder for Entity Framework 4.3 (or 4.3.1 or whatever is the current version in the future) there’s a tools directory and inside of there a migrate.exe command. It is the same as the update-database command with all of the same parameters.

migratecommandline

Entity Framework Moves to the Big House

Modified the original title of this post because it was derived from a misquote. Scott Hanselman clarifies with: The quote (what I said was) "EF is joining our team under ScottGu" and "EF is now the M in MVC". Scott Guthrie chimes in with “Yes – now part of my team (which includes ASPNET, WCF, WF, EF, Service Bus, BizTalk, Cache)”

_________________________________

Arthur Vickers, from the EF team, tweeted:

Also, very happy to be moving to @scottgu’s org with the rest of the Entity Framework team. Great for us, great for EF, great for Microsoft.

Just a reminder of Scott’s current role: “responsible for delivering the development platform for Windows Azure, as well as the .NET Framework and Visual Studio technologies used in building Web and server applications.”

A little later there was this on twitter from Noah Coad who is at Dallas Days of .NET (follow #dodn12 on twitter)

@shanselman at #dodn12 "just announced, we have an M in MVC, Entity Framework is now part of ASP.NET"

And then this interesting question from Daniel Bradley:

if Entity framework is to be part of ASP.NET, does this mean open-sourcing of the tools & framework?

Stay tuned….

(and since someone asked, EF has always been part of ADO.NET)

How I see Web API

Using OData in apps is so easy thanks to the RESTful API that lets us use HTTP directly & JSON results. But OData works directly against a data model with a limited set of operations and capabilities. You can do some customization but at some point you get beyond the point of data services.

So then it’s back to WCF Services where you can have oh so much control over the service but boy can it get complex, especially when you want to leverage various protocols in WS-* e.g., security, etc. And you have to speak the language of the service which is different from one service to the next.

I see Web API as potentially the best of both worlds. I get to have control of the logic in my service, but I can consume it very easily with HTTP.

Value add to my education and this post via Glenn Block: “Definitely a big value prop for Web API is allowing multiple devices to consume the same applications while at the same time taking advantage of client capabilities.”

 

 

webapi

New EF Code First Migrations Video on Pluralsight

My newest course is live on Pluralsight.com. This one is about using the new data migrations feature of Entity Framework Code First. These were first introduced with EF 4.3. Migrations lets you update your database schema when your model changes rather than having code first completely drop and recreate the database. This lets you retain data and any other existing database objects that aren’t described in the model (e.g., triggers, functions, etc.)

Entity Framework Code First Migrations
(total 1 hr 09 m)

  • Module 1: Introduction and Automatic Migrations
  • Module 2: Code-Based Migrations

Here’s the entire list of EF courses I’ve done for Pluralsight (so far Smile). I’ve sorted them in the order you might want to watch them in.

Entity Framework (8 courses)

Entity Framework 4.0 By Example
Beginner
[02:18:50]
27 Aug 2010

Entity Framework and Data Models
Intermediate
[01:31:38]
5 Nov 2010

Designer Supported EDM Customization
Intermediate
[02:05:13]
6 Jan 2011

Querying the Entity Framework
Intermediate
[01:22:37]
28 Feb 2011

Entity Framework 4.1 – Code First
Intermediate
[01:58:17]
18 Jun 2011

Entity Framework 4.1 – DbContext Data Access
Intermediate
[01:21:19]
27 Sep 2011

Data Layer Validation with Entity Framework 4.1+
Intermediate
[01:53:49]
8 Feb 2012

Entity Framework Code First Migrations
Intermediate
[01:09]
6 Mar 2012

Take care with EF 4.3 AddOrUpdate Method

EF 4.3 added a new extension method for DbSet called AddOrUpdate.

It is meant for use with seeding data during migrations.

It looks like a nice method to add into your apps but that’s not it’s purpose.

The job of AddOrUpdate is to ensure that you don’t create duplicates when you seed data during development.

First, it will execute a query in your database looking for a record where whatever you supplied as a key (first parameter) matches the mapped column value (or values)  supplied in the AddOrUpdate. So this is a little loosey-goosey for matching but perfectly fine for seeding design time data.

More importantly, if a match is found then the update will update all and null out any that weren’t in your AddOrUpdate.

For example, if your type is:

Person

  • Id
  • Name
  • UserName
  • CreateDate
  • Bio
  • Email

And there is a row in the database with

5, GiantPuppy, Sampson, 1/1/2011, I drool, gp@notarealdomain.com

And your AddOrUpdate has

context.Aliases.AddOrUpdate(
           a => a.Name,
           new Alias { Name = "GiantPuppy", UserName = "Sampson", CreateDate = DateTime.Now},
           new Alias { Name = "JulieLerman", UserName = "Julie", CreateDate = DateTime.Now}
         );

The method will look for a row where whatever column maps to the Name property has the value GiantPuppy. It will then update all of the mapped properties.

  • Name: GiantPuppy
  • UserName: Sampson
  • CreateDate: whatever the time is
  • Bio: null  (because it wasn’t provided)
  • Email: null (because it wasn’t provided)

This is about the same as doing an update in a disconnected app where you attach an object, mark it as modified and call SaveChanges. I see people do this in MVC apps all the time. If there are properties that were left null in the object because you didn’t care about them in this particular case, the database values will get overwritten with null. Except this is worse because it’s not leaning on your entity key (e.g. Id mapped to primary key).

So be careful out there. Me? I’m planning to use AddOrUpdate only for seeding migrations!

Update: I thought it would be useful to answer Livingston’s question here in the main post.

The update will update all of the properties it sees as changed.

It queries for the match (name==GiantPuppy), compares the values in the AddOrUpdate command to the results and updates anything that’s different.

So the results of the query would return the Id field for Giantpuppy. The migration will see that GiantPuppy’s seed Bioi(null) is different than the database Bio (“I drool”), that the email (null) is different than the database email and that the createdate value is also different. 

Here is the update command it sends to the database:

exec sp_executesql N’update [dbo].[Aliases]
set  [Email] = null, [Bio] = null, [CreateDate] = @0
where ([Id] = @1)
from [dbo].[Aliases]
where @@ROWCOUNT > 0 and [Id] = @1′,
N’@0 datetime2(7),@1 int’,@0=’2012-02-29 20:57:23.2779868′,@1=3

It’s updating everything that’s different…. email, bio and CreateDate.

DbContext Book is Online!

The digital version of Programming Entity Framework: DbContext is now available directly from O’Reilly Media at http://shop.oreilly.com/product/0636920022237.do.

This was a nice surprise since production only sent the final manuscript to the print production department yesterday. Smile

The print version might be another week or so.

Amazon will most likely have the kindle version available sooner than they are able to ship printed copies.

The what-if brain: Social pariah for developers?

As developers and analysts, we spend a lot of time asking “what if?”.

What if the user enters too many characters into this data entry field?

What if the network hiccups during a database save?

What if users are allowed to delete the record for this consecutively numbered item and then another user worries about a missing item #?

The longer we have been coding or working with domain owners to plan software, the more problems we can anticipate and ask “what if” about. It’s a good thing.

But this “talent” has had an adverse impact on my personal life. I can’t turn off the “what-if” brain.

What if I gain too much speed on this icy ski slope and can’t stop and … and … . (This one freezes me at the top of the slope while my friends stand waiting for me lower down wondering WTF is wrong with me.)

What if the dog sees someone across the road and runs to greet them and there’s a car coming up the road but they don’t see him heading down the driveway? (Been there, done that. I watched one of my dogs get hit and killed by a car years ago.)

What if we did something wrong with the woodstove before we left the house?

What if I order this menu item but change my mind by the time it arrives at the table?

Most of the people in my life who aren’t part of my developer-friends circle just don’t understand this.

My husband just thinks I’m a ridiculous worrier.

I’m afraid that my friend’s children will learn to be afraid of more things because of me.

My neighbors think I’m a complete lunatic about Sampson or any of their dogs in the road.

I don’t have an answer for this. I’m not about to let my guard down in my software development or in my life. But I do tend to explain my little problem as a job hazard– that I just can’t turn off the “what-if” brain just because I’m not in front of the computer.

You?

DbContext book status

largercoverThings are moving again! Our publisher had a production backup due to some staffing changes. Rowan and I are now reviewing the first version of the production manuscript (that is after they’ve converted our Microsoft Word documents into a single doc formatted for the final printing). We’ve got a PDF copy of that and are reading through and marking up any last changes we’d like to have fixed in the manuscript.

We’ve been told that the book will head to the printer (and digital production) on Feb 23rd. If it’s like the Code First book, the digital versions (PDF, mobi (aka kindle) and ebook from  O’Reilly and kindle from Amazon) will be available quickly with the print books to follow a week or so after that. Amazon has the book listed as “shipping March 8th” although I’m hoping that we see it sooner than that.

Links: