Posts
201
Comments
1111
Trackbacks
51
October 2010 Entries
Local PDC 10

On November 12, PDC is coming to Reston as part of the Local PDC EventsMy company is sponsoring the event which will be hosted at the Microsoft Technology Center is Reston, VA. Details of the 1-day event can be seen here.  The direct link register for this PDC event is here.

I will be presenting the talk on the updates for Visual Studio 2010. Vishwas Lele will be presenting the highlights from the PDC keynote.

Hope to see you there!

Posted On Thursday, October 28, 2010 5:05 PM | Comments (0)
CapArea and CMAP Presentations

Next week (Tuesday, October 26) I’ll be presenting Entity Framework 4 at CapArea. The following week (Tuesday, November 2) I’ll be presenting the same talk at CMAP. Hope to see you there!

Posted On Friday, October 22, 2010 12:55 PM | Comments (0)
Testing EF4 Code First Optimistic Concurrency with Fluent Assertions

Entity Framework 4 Code First CTP4 was released in July and the API for developing without any edmx continues to mature and get better. Code First allows you to define your entity framework configuration with a Fluent API similar to Fluent NHibernate. Although the API for EF Code First is very user friendly, you should still have integration tests to verify that you’ve configured your entities correctly. This post will walk through configuring EF4 Code First optimistic concurrency.

Suppose I have a POCO Task class that looks like this:

   1:  public class Task
   2:  {
   3:      public int Id { get; set; }
   4:      public string Name { get; set; }
   5:      public DateTime? DueDate { get; set; }
   6:      public int Status { get; set; }
   7:      public string Notes { get; set; }
   8:      public byte[] Timestamp { get; set; }
   9:  }

Notice on line #8 I have a byte array that I’ve named Timestamp. I’m going to map this to a SQL Server timestamp column. First I’ll create my DbContext. DbContext is a new type in EF Code Only that simplifies ObjectContext to streamline on the most frequently used methods.

   1:  class TasksDbContext : DbContext
   2:  {
   3:      public TasksDbContext(DbModel dbModel) : base(dbModel)
   4:      {
   5:      }
   6:   
   7:      public DbSet<Task> Tasks { get; set; }
   8:  }

Notice the constructor of my database context takes a DbModel. There are a couple of different ways I can create this. The first is to configure everything using the model builder like this:

   1:  var modelBuilder = new ModelBuilder();
   2:  modelBuilder.Entity<Task>().Property(m => m.Timestamp).IsConcurrencyToken().HasStoreType("timestamp").IsComputed();
   3:  var model = modelBuilder.CreateModel();
   4:  var context = new TasksDbContext(model);

The key is line #2 above where I fluently configure the timestamp property of my Tasks class to be 1) identified as a concurrency token, 2) specified as a SQL Server timestamp data type, and 3) a computed column so that EF knows that the user will not be inserting values into this field but rather, the value will be computed on the SQL Server itself. Although it’s syntactically convenient to be able to do all this inline with the ModelBuilder, as your apps get bigger, that can get ugly. In this case, it’s better to separate your configuration for each entity in EntityConfiguration classes like this:

   1:  class TaskConfiguration : EntityConfiguration<Task>
   2:  {
   3:      public TaskConfiguration()
   4:      {
   5:          this.Property(m => m.Timestamp).IsConcurrencyToken().HasStoreType("timestamp").IsComputed();
   6:      }
   7:  }

I’ve only added one line of configuration code here but, when I need to specify additional mapping/configuration details about the Task entity, I’ll do it here.  Now I can simply reference that entity configuration with the model builder. Hence, I’ll create a simple context factory class:

   1:  class ContextFactory
   2:  {
   3:      private static DbModel dbModel = InitializeModel();
   4:   
   5:      private static DbModel InitializeModel()
   6:      {
   7:          var modelBuilder = new ModelBuilder();
   8:          modelBuilder.Configurations.Add(new TaskConfiguration());
   9:          return modelBuilder.CreateModel();
  10:      }
  11:   
  12:      public static TasksDbContext CreateContext()
  13:      {
  14:          return new TasksDbContext(dbModel);
  15:      }
  16:  }

Now anytime I need a database context, I can just call my factory method. Before we get to integration testing our data access code, let’s wrap up our EF code in a simple repository so our consumers don’t need any knowledge of EF.

   1:  public class TaskRepository : IRepository<Task>
   2:  {
   3:      public void Add(Task item)
   4:      {
   5:          using (var context = ContextFactory.CreateContext())
   6:          {
   7:              context.Tasks.Add(item);
   8:              context.SaveChanges();
   9:          }
  10:      }
  11:   
  12:      public void Update(Task item)
  13:      {
  14:          using (var context = ContextFactory.CreateContext())
  15:          {
  16:              context.Tasks.Attach(item);
  17:              context.ChangeObjectState(item, System.Data.EntityState.Modified);
  18:              context.SaveChanges();
  19:          }
  20:      }
  21:   
  22:      public Task FindById(int id)
  23:      {
  24:          using (var context = ContextFactory.CreateContext())
  25:          {
  26:              return context.Tasks.FirstOrDefault(x => x.Id == id);
  27:          }
  28:      }
  29:      // Remove() and FindAll() methods omitted for brevity
  30:  }

A couple things of note: first, I’m simply using my ContextFactory to create the context anytime I need it. Second, notice line #17 above calls a method on the database context called ChangeObjectState(). I added this method to TasksDBContext in order to get at the ObjectStateManager in the ObjectContext. This allows me to mark an entity as modified (i.e., a UPDATE should occur) that came in from another tier and was created in another context somewhere. The entire method looks like this:

   1:  public void ChangeObjectState<T>(T entity, EntityState entityState)
   2:  {
   3:      this.ObjectContext.ObjectStateManager.ChangeObjectState(entity, entityState);
   4:  }

In EF4 DbContext, the ObjectContext is a protected property. Hence, if you want to get at it, you have to do so in the context itself (i.e., I could not have referred to it from my repository directly).

At this point, we’re ready to execute our integration tests. To do this, I’m going to use MSTest with Fluent Assertions. Fluent Assertions is a CodePlex project that enables you to use a fluent-style API to more natural specify your expected outcome. The API for MSTest has been basically stagnant for the last several years and this adds functionality onto it so you can use MSTest and still get the benefit of fluent assertions. Additionally, Fluent Assertions enables us to get away from the clumsy [ExpectedException] attribute to a more deterministic xUnit-style ShouldThrow() API.

Our unit test will have two different repositories (and therefore 2 different contexts) get the same task. Then the first repository will save. When the second repository saves, we’ll expect an OptimisticConcurrencyException:

   1:  [TestMethod]
   2:  public void Save_with_wrong_timestamp_should_fail()
   3:  {
   4:      // arrange
   5:      var taskId = 1;
   6:   
   7:      var repository1 = new TaskRepository();
   8:      var task1 = repository1.FindById(taskId);
   9:   
  10:      var repository2 = new TaskRepository();
  11:      var task2 = repository2.FindById(taskId);
  12:   
  13:      task1.Notes = "modified note";
  14:      repository1.Update(task1);
  15:      task1.Notes.Should().Be("modified note");
  16:   
  17:      task2.Notes = "modified note 2";
  18:   
  19:      // act
  20:      Action action = () => repository2.Update(task2);
  21:   
  22:      // assert
  23:      action.ShouldThrow<OptimisticConcurrencyException>();
  24:  }

Notice line #15 above – it shows a simple example of the Should().Be() syntax that Fluent Assertions gives you for MSTest. Next look at line #20 and #23. Here is see we are deterministically asserting that that specific line of code *will* throw the expected exception. This is much better than the [ExpectedException] attribute as that could give false positives given that *any* line of code in your unit test could potentially cause an exception.

As a final step, let’s check out what happens behind the scenes when this test runs by using the Entity Framework Profiler. This tool is not free but it’s simply the best tool I’ve seen for profiling EF where people typically resort to using the SQL Profiler. If you’re doing any serious EF work, it’s *definitely* worth the money. To use the EF Prof, just add the required assembly per the documentation (HibernatingRhinos.Profiler.Appender.v4.0.dll) and then add the 1-line code to the beginning of your method: EntityFrameworkProfiler.Initialize();

 

efprofoptcon

 

There are a couple of interesting things to notice in our EF Prof output. First, the WHERE clause on line #6-7 above shows what we’d expect with Optimistic Concurrency – that is, it looks at both the Id *and* the concurrency token column.  The second interesting thing is that EF prof is showing a red alert bubble. When we click on this we see, “Transaction disposed without explicit rollback/commit”. So EF Prof not only shows you the complete profiling results but also suggests ways to improve your code.

Certainly data access code is nothing new. However, with EF4 Code First, integration testing with Fluent Assertions, and debugging with EF Prof, I must say, it’s more fun than it’s been in a while. I highly recommend checking all these out.

Posted On Monday, October 11, 2010 10:01 PM | Comments (12)

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud