Entity Framework 4.1 Inheritance – Table per Hierarchy

By default if you apply inheritance in Entity Framework 4.1 the model that will be used is table per Hierarchy. Meaning that this object model:Will be translated to this table in your database:

So we get one table containing all the fields from all the classes in the hierarchy and one additional discriminator column which will be filled with the name of the class. Using that value EF knows what class it needs to create an instance from. Create a mapping for this manually would be done by subclassing DbContext and implement OnModelCreating as illustrated in the following piece of code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Map(x => x.ToTable("Products"))
        .Map<Book>(x => x.ToTable("Products"))
        .Map<Movie>(x=>x.ToTable("Products"))
        .Map<Cd>(x => x.ToTable("Products"));
    base.OnModelCreating(modelBuilder);
}

Entity Framework 4.1 Material

Gave a quick intro on what’s new in entity framework 4.1 to my co-workers. You can get the slides and the code.

If you want to get started documentation is at the moment a bit lacking, there is some info on MSDN but you’ll find more on the ADO.NET team blog, especially this 12 part article.

Yesterday the power tools for Entity Framework 4.1 were released, you can read all about them over here.

There are some features that didn’t make it into Entity Framework code first but that are available if you use one of the “older” approaches, Microsoft is quite open about it, which I think is very honest. You can read about those on the MSDN site as well.

There’s also some material that was available in the latest CTP material but didn’t ship in 1.0. Let’s hope they’ll come in the next release.

MVC3 and MonoDevelop

Just a quick update to list the assemblies you need to copy to make MVC3 work with Mono and MonoDevelop. On my Mac I opened a Visual Studio solution, I deleted all the entity framework references from my MVC project, won’t use it anyway, and then copied these assemblies to a local folder since they are not part of the Mono framework:

  • System.Web.Helpers
  • System.Web.Mvc
  • System.Web.Razor
  • System.Web.WebPages.Deployment
  • System.Web.WebPages
  • System.Web.WebPages.Razor

Fix the references in your project, hit run and you’re good to go. Unfortunately you’re not getting any intellisense yet.

Book review: Essential LINQ

A few months ago I wanted to look into LINQ to SQL and grabbed a copy of Essential LINQ. The book is targeted at people who are coming from .NET 2.0 or people who are new to LINQ. It’s is very well written, almost like you’re following a class with clear examples showing you how you can leverage the platform to suit your needs.

Essential LINQ

The new language features of .NET 3.0 are covered which enable LINQ in the first place so if that’s new for you no need to buy another book. All LINQ operators are explained using LINQ to Objects followed by a very thorough discussion of LINQ to SQL. Mapping, stored procedures, modifying objects and how you can plug into the system with extension methods. After diving deep into LINQ to SQL there’s only a very small description of the Entity Framework or LINQ to Entities. Which is probably, in hindsight, the biggest issue you can have with this book since it’s now the de facto standard of data access promoted by Microsoft. The book finishes with another in depth discussion of LINQ to XML which was new to me and just like LINQ to SQL you’ll be an expert by the end of the chapters.

So to wrap it up, the book reads like you’re being thaught by a very good teacher. If you want to make sure you know your basic LINQ this is the one you need.

Book review: Silverlight 4 in Action

In order to prepare for a Silverlight course I was going to give I looked around for some new books and material to help my students and to refresh my knowledge. If you want to get started from zero on Silverlight I can highly recommend Silverlight 4 in Action. It’s an updated version from Silverlight 2 in Action and available since August 2010 via Manning.

Silverlight 4 in Action

The book is divided in three parts with the first two giving you all the necessary information to get you started and a third part which digs deeper into some more special topics.

In part one you’re introduced to Silverlight, how it relates to WPF and why you could choose it to build your next application. You get an overview of XAML and browser and desktop integration options. While it’s just the first part of the book, don’t think it’s just for newbies. You get an in depth explanation on how the rendering system works, what the different types of controls are and how text can be used.

Part two gives you all the information you need to build real applications. You’re introduced to the binding features, what your options are for data validation and how you can communicate with other applications. Either Silverlight plugins on the same page or other systems via web services. The last two chapters also give a nice explanation of the MVVM pattern, although it goes way further and shows you ways to improve the maintainability of your code. Very nice to see SOLID and DRY come into play hopefully we’ll see more developers using those principles. The last chapter covers WCF RIA services, these were new to me and I was a bit blown away by the functionality that’s available out of the box, though I’m still a bit sceptic. It might be a bit too much forms over data even though there are some layers in between where you can plug into to do your thing.

The last part adds chapters on working with graphics, creating animations, improving the install experience, using styles and resources and creating custom controls. Some of those you’ll use often, printing for instance, others maybe once in a lifetime, like creating a custom panel.

Overall a very nice read to introduce you to the platform and create real world applications. It’s definitely developer oriented though, don’t expect to see much Expression Blend which you’ll use to create themes and animations which I don’t think you’ll be doing in code as illustrated in the book.

CRM 4.0 Support

A colleague of mine was fighting with CRM 4.0 at a client side. He was able to fix all their issues except one. They had changed from HTTP to HTTPS after installation and from that point on no one could connect externally. Anytime you changed something in the Outlook client the response was “The underlying connection was closed: an unexpected error occurred on a send.”. Not that much information to work with so I helped him to get the issue fixed. We dug through some log files to get some more information and found out that it was actually the audit plugin/service which was complaining with “the handshake failed due to an unexpected packet format”. Which clearly indicated it was something with the certificate or a specific HTTPS issue. Long story short, you need to change a registry value from port 80 to 443. We found all the necessary information on these sites:

How to support Contains in Entity Framework 3.5

How can you retrieve the products that are contained in a list of id’s ?

var ids = new List<int>() { 1, 2, 3, 500 };
using (var context = new AdventureWorksEntities())
{
  var products = from product in context.Products
                           where ids.Contains(product.ProductID)
                           select product;
  WriteProducts(products);
}

The good news, this is supported in Entity Framework v4.0, but since I’m on 3.5 I needed to find another solution. Luckily using the info from my previous post I can write an expression for this:

var ids = new List<int>() { 1, 2, 3, 500 };
using (var context = new AdventureWorksEntities())
{
  Expression<Func<Product, bool>> idMatching = null; 
  foreach (var id in ids)
  {
    int productId = id;
    if(idMatching == null)
    {
      idMatching = x => x.ProductID == productId;
    }
    else
    {
      idMatching = idMatching.Or(x => x.ProductID == productId);
    }
  }
  var products = context.Products.Where(idMatching);
  WriteProducts(products);
}

Combining expressions to use with the Entity Framework

You often have to create a screen where the information is filtered on a given condition and the user can set some more options through checkboxes. For instance, display all products of a certain category and those results should be able to be filtered on their active status.

We could send one query to the database to retrieve the products and then filter them in memory, but let’s try to use the database for all of this since they’re good at this. You’ll bump into several issues when trying to solve this and like most problems in software development someone else most likely encountered the same issue and has already found a solution. In this case take a look at this, albeit old, article which illustrates the problem and gives a solution. It will enable you to write code like this:

public class ProductFinder
{
  public  ICollection<Product> FindProductsBySubCategory(int subCategoryId, bool makeFlagMarked)
  {
    using(var context = new AdventureWorksEntities())
    {
      Expression<Func<Product, bool>> whereClause = x => x.ProductSubcategory.ProductSubcategoryID == subCategoryId; 
      if(makeFlagMarked)
      {
        whereClause = whereClause.And(x => x.MakeFlag);
      }
      return context.Products.Where(whereClause).ToList();
    }
  }
}

Changing Entity Framework model at runtime

Out of the box there is no way, or at least not an easy one, to change table or schema names used by the Entity Framework at runtime. If you used MyDbName.dbo.BlogPosts as table name during development you can not use MyDbName.dbo.CustomerA_BlogPosts if you want to support customer specific table names as explained in my previous post.

On CodePlex however you can find an adapter for your Entity Framework model to change it at runtime. You can change the connection to the database, change table names or use different schemas. So a lot of goodness to support multi tenant applications.

In order to use the adapter you should create a partial class with the name of your context class and inherit from AdaptingContext instead of ObjectContext.

public partial class AdventureWorksEntities
  : AdaptingObjectContext
{
  public AdventureWorksEntities()
    :base("name=AdventureWorksEntities", "AdventureWorksEntities",
            new ConnectionAdapter(new TablePrefixModelAdapter("MyPrefix"), Assembly.GetExecutingAssembly()))
  {
    OnContextCreated();
  }
}

This partial class has the same name as the partial class generated by the Entity Framework. You should remove the generated constructors and base class specification from that one or your code will not compile. Note that every time you update the model with the designer it will regenerate the constructors etc. so you have to remove them every time.

In this example I’m using the TablePrefixModelAdapter which will prefix all my tables with my specified prefix, in this case “MyPrefix”. Consuming this context is done just like a normal ObjectContext. You also need to specify where the mappings that need to be altered are located, in this sample I’m using a single console application so they are contained in the executing assembly.

using(var context = new AdventureWorksEntities())
{
  var products = context.Products;
  products.ToList().ForEach(x => Console.Write(x.Name));
}

And this generates the following SQL:

SELECT 
1 AS [C1], 
[Extent1].[ProductID] AS [ProductID], 
[Extent1].[Name] AS [Name], 
[Extent1].[ProductNumber] AS [ProductNumber], 
... 
FROM [Production].[MyPrefixProduct] AS [Extent1]

So we’re all set to support multi tenancy? Not quite. The code as available in the CodePlex project stores the updated mappings in a static variable for performance reasons, this is great if you’re developing against a development database and your code will run against a production database with different naming or schema.

For a multi tenant application we need a different model for each of our customers so we need to make another change to the code as available in the CodePlex project. If you don’t mind taking the performance hit to rewrite the mapping every single time an object context is created you can just open the ConnectionAdapter class and change the static variables which hold the model information to instance variables.

And optimized version would store all the mappings per customer so you only rewrite the mappings once a new customer hits the context, and from that point store them in i.e. a dictionary with key the customerID and value the updated mappings.

I’ve used Entity Framework 3.5 SP1 and Visual Studio 2008 in this post.

Covering multi tenancy in the database

You there, computer man! Make it a multi tenant application.

There are several ways to support multi tenancy on the database part of your application. The easiest approach would be to add a CustomerID column to each table. This is easy to maintain since any change you make in your development environment (add a column, change a type,…) needs to be done only once on the live environment. The downside however is that all data of all your customers is mixed in one table forcing you to add a where clause to all your queries to filter on the customer id, if you support different business logic per customer you might also run into issues. Customer A wants an additional field etc.

Another approach is to prefix or suffix your table names with some sort of customer identification. So you’d have CustomerA_BlogPosts, CustomerB_BlogPosts. You can have a single database for all your customers but now all data is stored in a different table. Since now you have multiple tables representing the same model you’ll have to figure out a way to migrate to new versions. It’s doable but keep it in mind, you’d also have to create some infrastructure to select the correct table when you issues your queries.

A variant on the customer specific table names is to create database schemas which are specific to your customer. So you’ll have CustomerA.BlogPosts and CustomerB.BlogPosts. Apart from the fact that all data is stored in specific tables per customer, like the approach stated above, you can also add an additional security layer by using a specific database user per customer which can only access the tables of the specific schema. All table names remain the same so you could even migrate specific customers to another database server as long as your infrastructure to look up the correct database / schema name.

The most flexible way however, but with quite an impact on your server, is to create an entire database instance per customer, this gives you the most available options. You can use all available database tooling to revert specific databases if the customer asks you to etc.

I’ve used all approaches stated in this post and even mixed and matched between them, it all depends on the scale and requirements of your project. For small projects I’d use the first approach with the additional column. For larger projects or where you need to support different data models per customer the schema specific approach or the entire database per customer are the way to go in my opinion.