Tuesday, February 28, 2012

Experiencing Entity Framework - Code First

I spent most of my time lately on learning Entity Framework, and the latest and the coolest Code-First. It is a nice tool overall, but one can realize that the object-relational mapping (ORM) is a huge world, and this tool, already reached version 4.3, still has a long way to go. I hope some day version XXX can be mature enough so one does not need to keep on pounding it, and ask: "Why isn't this supported?"

This post is my attempt to document some of the road blocks that I've encountered:

Cannot use a discriminator field as part of the key.

I'm designing a system that can use external web-services, such as Facebook, Google, and etc, to authenticate a user. So a user can have multiple 'identities' (Facebook identity, Google identity, and etc). Any of these identities is enough to authenticate the user. So, I have an abstract base class called UserIdentity. I also have 2 concrete classes: FacebookUserIdentity and GoogleUserIdentity:

public abstract class UserIdentity
{
    public string UserKey { get; set; }
}

public class FacebookUserIdentity : UserIdentity
{
    public string SomeFacebookSpecificData { get; set; }
}

public class GoogleUserIdentity : UserIdentity
{
    public string SomeGoogleSpecificData { get; set; }
}

There are some fields that I can use to be the key of the entity, rather than defining another int or Guid property. UserIdentity.UserKey is a value provided by these external web-services to identify the user. It can be part of the key, but not the whole key, because different services may issue out the same UserKey. Therefore, it is logical to add the name of the service (Facebook, Google) as part of the key. This is naturally the "Discriminator" field which is used by Entity Framework to determine the type of the class. The problem is I cannot add the discriminator field as part of the key.

 
There is no way to define a unique constraint.

Many people have complained about this. They also complain that they cannot add database indexes via Entity Framework. My opinion is that defining database indexes is not the responsibility of an ORM tool. The ability of creating databases from some ORM tools (like Entity Framework) have misled people to think that they should 'define' the database in an ORM tool. An ORM tool, by definition, should provide data mapping only. So, should it support unique constraint? Yah, why not? Now I have been mislead too.


No comments:

Post a Comment