Monthly Archives: June 2011

EF4 books and EF 4.1

I’ve been asked repeatedly about the viability of my book, Programming Entity Framework, and the other EF4 books out there now that EF 4.1 has been released.

The EF4 books are still totally viable and important if you truly want to learn Entity Framework for the purpose of writing enterprise applications.

Entity Framework 4.1 simply adds two new features to Entity Framework. The first is an additional way to create a model, called “Code First”, the second is a stripped down version of the ObjectContext. They are *awesome* additions for those who like to program this way. And you can always hook back to the ObjectContext if/when you want to get the granular control you will likely need if you’re writing an enterprise app. I love code first and I love the DbContext. But I also love Database First for many scenarios, Model First for many scenarios and the extreme power that the ObjectContext provides me when I want it. And when I’m writing real apps, not just demos, I definitely want the ObjectContext available to me!

But…

The core APIs don’t change.

The need to understand the ins and outs of the conceptual model and mappings doesn’t change.

The need to understand how to use EF in an application shifts at the surface, but if you need to do more than simple drag & drop applications, you’ll need to understand how to work with the underlying API.

The need to understand how EF works and how you can manipulate to improve performance, to do threading, to control transactions does not change.

The need to understand how changes are tracked and how relationships are managed and how to affect those features so that you can make application back ends work the way you want them to does not change.

Currently my recommendation is that if you think you want to use Code First and the DbContext, take a look at what’s in there (great blog posts by EF team at blogs.msdn.com/adonet, a series of 11 short videos (with accompanying articles and download samples) that I created for MSDN at msdn.com/data/ef, a new EF 4.1 course (and more coming) on Pluralsight and many articles & blog posts written by very knowledgeable community members) to learn how to use code first and DbContext when working with EF.

But if you are writing applications with Entity Framework, you’ll still want to learn how to program with it. And for that, you have three great books that you can learn from – all take a different approach and they are quite complementary to each other. Yes, mine is one of them and of course I recommend it. I spent a year on the first edition and another year on the second edition. I worked very hard to learn EF inside and out to help you learn it, too. I also recommend Entity Framework 4.0 Recipes and Entity Framework 4 in Action. Again, these books take a very different approach than mine and in my opinion, the three books complement each other nicely.

In case you think this might be a desperate attempt to sell more books, it is hardly that. Tech book authors get a *very* small royalty per book sold. Tech book writing is not typically a financially rewarding endeavor. Instead, the desperate attempt I’m making is to offer a better explanation for the many people who keep asking me when I will be updating my book to EF 4.1 – a better response than I can provide in the 140 characters on twitter.

The out of band release of EF 4.1 may be followed by others so right now EF is a moving target. Updating Programming Entity Framework to incorporate the new features just doesn’t make sense. I think using the core books to learn EF and then supplementing with the EF 4.1 content that can be produced and shared more quickly (online articles & videos from trusted resources) is your best bet.

Turning off Code First Database Initialization completely

I was using a hack to turn off the Database Initialization for code first. I didn’t want code first to do the model/database comparison, and found the best way I could figure out…I deleted the EDMMetadata table in the database.

Yes, a total hack.

Sergey Barskiy and Rowan Miller straightened me out.

Even though the custom conventions did not make it into EF 4.1, there are still some controls for the default conventions. I had totally forgotten about this. But this gives you one of the ways to turn of the initialization.

You do this in the OnModelCreating override in the context class:

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
     }

That’s System.Data.Entity.Infrastructure.IncludeMetadataConvention, if you are curious about which namespace I’m using.

The other way is to set the DbInitialization strategy go null (as opposed to letting code first just use the default “CreateDatabaseWhenNotExist”, or using one of the others e.g. “DropCreateDatabaseWhenModelChanges” or even a custom strategy that you’ve created based on one of the built in strategies.

You typically set DbInitialization strategies at application startup, for example in global.asax for web apps and you do the same even if you are setting it to null.

Here’s an example of how to do that given that I have a context class called BlogContext that inherits from DbContext:

 Database.SetInitializer<BlogContext>(null);

MVC3.1 Scaffolding Magic with Database (or Model) First , Not Just Code First

The MVC3.1 scaffolding that was released at Mix can auto-magically create an EF 4.1 DBContext class, the basic CRUD code in your controller and the relevant views all in one fell swoop. (Don’t forget the additional scaffolding tools that will build things more intelligently, i.e. with a Repository (http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/).

All of the demos of this, including my own [MVC 3 and EF 4.1 Code First: Here are my classes, now you do the rest, kthxbai] demonstrate the new scaffolding using Code First. In other words, just provide some classes and the scaffold will do the rest, including build the context class.

 I saw a note on twitter from someone asking about using this feature with an EDMX file instead of going the code first way. You can absolutely do that. Here’s a simple demo of how that works and I’m using the in-the-box template in the MVC 3.1 toolkit  — though admittedly, for my own purposes, I’m more likely start with the template that creates a repository.

 1) Start with a class library project where I’ve created a database first EDMX file.

step1dbfirstmodel

2) Use the designer’s “Add Code Generation Item” and select the DbContext T4 template included with Entity Framework 4.1. That will add two templates to the project. The first creates a DbContext and the second creates a set of very simple classes – one for each of the entities in your model.

 step2codegendbcontext    

       step2dbcontextclasses

3) Add an ASP.NET MVC3 project to the solution.

 step4 new mvc

4) Add a reference to the project with the model.

step5 ref model project

5) BUILD THE SOLUTION! This way the Controller wizard will find the classes in the other project.

6) Copy the connection string from the model project’s app.config into the mvc project’s web.config. Step 7 will complain otherwise.

step7 copy connection string

7) Add a new controller to the project. Use the new scaffolding template (Controller with read/write actions and views using EF) and choose the generated class you want the controller for AND the generated context from the other project.

step7 controller

That will create the controller and the views. The controller has all of the super-basic data access code for read/write/update/delete of the class you selected. It’s a start. Smile

step8 create

Almost ready to run but first a bit of house keeping.

8) The most common step to forget! Modify the global.asax which will look for the Home controller by default. Change it so that the routing looks for your new controller.

step9 globalasax

 9) Time to test out the app. Here’s the home page. I did some editing also. It all just works.

volia

I highly recommend checking out the alternate scaffolding templates available in the mvc3 scaffolding package linked to above.

Code First’s Column DataAnnotation and the ORDER attribute

The ColumnAttribute lets you change three things about property mapping to database columns.

  1. The name
  2. The order in which it appears in the field list in the table
  3. The type

If you look at the documentation for ORDER on ColumnAttribute it simply tells you that its “zero-based” and I comletely misundestood that.

I set a property’s order to “1”

[Column("DateStarted",Order=1,TypeName ="date")]
       public DateTime CreateDate { get; set; }

expecting it to magically become the 2nd column listed in the table.

But it was the first.

Here’s why with thanks to David DeWinter for pointing me in the right direction.

The value is relative to all other properties.

And all of the other properties are not 0, 1, 2, 3, etc.

The default is Int32.Max, i.e. 2,147,483,647.

So my DateStarted field had the lowest value after all. It was Order=1 while all of the others were Order=2,147,483,647.

You’d see the effect better if you set the order on a number of the properties. The lowest # you can use is zero, which is where “zero-based” comes in.

Might have been obvious to others, but I was awfully confused. But you know, it’s Friday afternoon….

And I’ve been told the docs will get a clarification. 🙂