Julia Lerman's Blog, page 20

March 9, 2012

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)

 •  0 comments  •  flag
Share on Twitter
Published on March 09, 2012 09:06

March 8, 2012

How I see Web API

Using OData in apps is so easy thanks to REST & JSON. 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 REST.

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

 •  0 comments  •  flag
Share on Twitter
Published on March 08, 2012 11:28

March 7, 2012

Almost Vermont IT Jobs: .NET devs needed in Lebanon, NH

COMPUTAC INC is looking for PROGRAMMERS with experience in Microsoft VB6, VB.NET,  ASP.NET, Win Form Development, N-tier design concepts and MS SQL server database (design, maintain, and administer). To learn more please contact us, or send your resume to vern@computac.com.

Vern Gourley
Computac Inc
162 North Main Street
West Lebanon, NH 03784
(603) 298 –5721
www.computac.com

 •  0 comments  •  flag
Share on Twitter
Published on March 07, 2012 10:53

Table of Contents for DbContext Book

Here are screenshots of the table of contents (well really the PDF bookmarks) for Programming Entity Framework: DbContext so you can get an idea of what's in there.

From O'Reilly Media (publisher): http://shop.oreilly.com/product/0636920022237.do.

From Amazon: http://juliel.me/xnayHq

toc1

toc2

 •  0 comments  •  flag
Share on Twitter
Published on March 07, 2012 04:51

March 6, 2012

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.)

(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)

Beginner
[02:18:50]
27 Aug 2010

Intermediate
[01:31:38]
5 Nov 2010

Intermediate
[02:05:13]
6 Jan 2011

Intermediate
[01:22:37]
28 Feb 2011

Intermediate
[01:58:17]
18 Jun 2011

Intermediate
[01:21:19]
27 Sep 2011

Intermediate
[01:53:49]
8 Feb 2012

Intermediate
[01:09]
6 Mar 2012

 •  0 comments  •  flag
Share on Twitter
Published on March 06, 2012 18:43

February 29, 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.

 •  0 comments  •  flag
Share on Twitter
Published on February 29, 2012 15:32

February 24, 2012

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.

 •  0 comments  •  flag
Share on Twitter
Published on February 24, 2012 11:53

February 22, 2012

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?

 •  0 comments  •  flag
Share on Twitter
Published on February 22, 2012 06:23

February 19, 2012

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:

DbContext book on O'Reilly.com DbContext book at Amazon.com Code First book on O'Reilly.com Code First book on Amazon.com "the big book" Programming Entity Framework 2nd edition
 •  0 comments  •  flag
Share on Twitter
Published on February 19, 2012 09:06

February 16, 2012

Using EF 4.3 Code First Migrations with an Existing Database

In working on my upcoming EF 4.3 Migrations video for Pluralsight, I wanted to work out how to use this with an existing database where I plan to add new types and therefore want migrations to not just use this database, but migrate it as well. Problem solved*, but then I tried to use it in a production application and found an easy-to-fix problem. So…I thought I'd share the process in a blog post while it's on my mind.

The Purpose of the Migration-History Table

When you let EF 4.3 code first create a database for you, it inserts a Migration-History table into the new database. It's hidden in System Tables. This is equivalent (in a way) to the EdmMetadata table you would have gotten with EF 4.1 & 4.2.

The table is used by two processes (maybe more that I haven't encountered yet).

When you run the app using automatic migrations, if it's doing any type of data initialization, it will check that Migration-History table to see if the database needs to be updated.

If you are using code-based migrations, Update-Database will also look at the Migration-History table.

If there's no migration-history table (which there won't be in an existing database), the model won't be verified against the database with automatic migrations.

So you need to get that table into your existing database.

That table is created using the most recent migration file in your data layer.

Getting a Migration-History table into an existing database

If you're starting with a new app, you won't have that either.

So

Step 1) In Package Manager Console, execute "add-migration initial".

This will force code first to create a migration class (which I chose to name "initial") based on the code first model. It will have migration code to create all of the necessary database tables (based on what it's found in the model) with their columns, keys and constraints.

But your database already exists! If you were to try to execute that migration and you have entities that map to those existing tables, EF will try to create the tables and tell you that the tables already exist.

Step 2) remove all code that duplicates existing tables from inside the Up and Down override methods in the initial migration. But, leave the methods there.

This is a little tricky. I find that it's safer to do this when there's nothing in my model yet that would required a database modification. That way it's all clean. I've done this when I had one new class and then I had to start over again to get the true "initial database" and then start making any mods I want to my model.

Now, code first has a migration that contains no database modification code. That represents how things are at the beginning of EF 4.3 migrations involvement in your app.

Step 3) run Update-Database

This will do two things. It will execute the Up method in the initial migration, which has no effect on the database. And it will create the Migration-History table in your database based on the current state of the model. That way, if you are using automatic migrations, next time Code First does db initialization, it will compare the current model to the one stored in the migration-history to determine if the database needs to be migrated/updated.

Now you can evolve your app and let code first fix up your development database as needed.

The problem I encountered? A SQL Server 2000 Database

I was doing this with an existing client database (not production, but a copy for development … just sayin'  Winking smile)

When running Update-Database I got the following error:

Conversion failed when converting date and/or time from character string.

Remember I'm not really updating my database. This was when code first was trying to create the Migration-History table.

It is an old database that has been recently updated to SS2008. Even though I'm using SQL Server 2008R2, that database was still set as a SQL Server 2000 database and was not happy with the format of the date field in the INSERT command:

INSERT INTO [__MigrationHistory]
([MigrationId], [CreatedOn], [Model], [ProductVersion])
VALUES ('201202161546124_initial', '2012-02-16T15:55:56.252Z',
[big-ass hash you don't need to see], '4.3.0')


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Luckily, I was able to just update my database version to 2008  and the insert command succeeded with no problem.



*still finding some more interesting tasks I have to do. For example, as I ensure that my model mappings reflect the database, I have to rewrite my initial migration and delete the migration-history table (there might be a scaffold command for that but I'm doing it in SSMS) and call update-database again.

 •  0 comments  •  flag
Share on Twitter
Published on February 16, 2012 08:20

Julia Lerman's Blog

Julia Lerman
Julia Lerman isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Julia Lerman's blog with rss.