Entity Framework 5.0 requires you to use .Net 4.5 with Enum support

You can migrate your EF4.5 to EF5.0 without the need of Microsoft .Net but if you use some features like the support of enumeration that provide EF5.0 you will need to have the .Net Framework 4.5.

What does it means? It means that you need to have Visual Studio 2012. So a simple migration of Entity Framework 5.0 became an endeavour of few hours but at the end work well.

I think it worth it if the business you are working on accept to change their tool (VS2010 to VS2012).

What is the implication of migrating Entity Framework 4 to Entity Framework 5?

I had to take care about updating Entity Framework from version 4.3 to version 5. Even if the Framework has been released about 2 weeks ago and this might looks rapid, it’s not that much. It’s not because it has been in RC since few months and in beta for even more time. Some time, instead of fighting against feature like keeping adding classes to support enumeration or to do some gymnastic with C# to turn around bugs it’s just a better idea to upgrade.

First of all, we use NutGet to get the package but we do not use the default mechanism. Once downloaded, we take the dll and we move them into a specify DLL directory. You may not have to do this, but sometime politic force you do to it so the first step was to copy the DLL.

However, unlike Entity Framework version 4.0 to 4.1 or to 4.3… Entity Framework version 5 contains 2 DLL. One compiled with the version of Microsoft .Net Framework 4.0 and one with version 4.5. Since we haven’t switch to 4.5 yet, I had to copy the version 4.0.

Once the DLL changed, and the validation that the project is well referenced to this new dll. I hit the compile button and see many errors that has been fixed rapidly.

Namespace changes

The first think you have to know is if you use data annotation, the namespace has changed.

using System.ComponentModel.DataAnnotations;

became:

using System.ComponentModel.DataAnnotations.Schema;

So you have to change some of your classes to use the new Schema. This was required for us because we use data annotation (not a lot but still over hundred places).

NotMappedAttribute is not NotMapped

I don’t know why but the application I am working one use sometime NotMapped and sometime NotMappedAttribute. Well, with Entity Framework 5.0, NotMappedAttribute doesn’t work. It’s now only NotMapped.

And that was it. Not a big deal. We are using Code First, so, no EDMX file is present and so than nothing to update. The DbContext hasn’t change and everything compiled correctly. The migration of EF4 to EF5 tooks 10 minutes, this is what I like!

CSS block, inline and inline-block comparison

What is the difference between an element with display block, display inline and display inline-block? It’s all about the element way to take the space within the Html.

Display Block

The display block let you specify a width, a height and act as a block of space. If you want to have something to its right, the element will need to float because by default, the block won’t let anyone being around it. It also let you use margin attribute. By default, header tag like H1 use block and you won’t be able to add anything to its right. It will goes automatically to under it. Same thing happen if you use the paragraph tag “p”.

Display Inline

This is the opposite. It will take only the space required, won’t let you set width or height. This is perfect if you want to have add tag within an element. This is the default value for “span” tag. But, this won’t let you use margin and sizing feature.

Display Inline-Block

The main goal of inline block is to preserve its block capabilities such as width and height, top and bottom margins and paddings.

So that’s it for display value. Of course you can set display:none if you want to remove the element and its space (inverse of visible which will remove the visual aspect while preserving the space). You can also use display:list-item if you want to act like list “li” which will add bullet to every rows. This is acting like display:block with bullet.

Review of NDepend

NDepend is an analysis tool for Microsoft .Net code. The primary goal of this tool is to let you know about the quality of your code with some metrics.

You can use NDepend as a software or as a Visual Studio Add-in. I tried both and prefered the standalone application. I found it easier to use and also didn’t find any real advantage to have it integrated into Visual Studio. Nevertheless, it can become handy to have it inside Visual Studio if your daily task is to optimize .Net code.

I did a run with the open source project called Nerd Dinner which is a MVC3 application. The version of Nerd Dinner is 77871 and the version of NDepend is 4.0.2 Professional edition.

The way it works is that you ahve to create a new project inside NDepend. This will allow you to not have to configure every time where are the assemblies to analyse and also give you the opportunity to compare in time the progression of your changes.

Once the project is done, you will be landed to the main user interface of the application with the project’s properties windows open. This will let you choose assembly or directly the solution file to analyse.

For my test, I choose the solution file which contain 2 projects, the main website and the testing project. Once selected you just need to press the Play button and the selected files will be analysed. Nerd Dinner is a very small project and it took 4 seconds to analyse. When the analyse is done, your browser will popup a webpage with a report.
. The advantage of the web report is that it let you send the report without having to use the tool NDepend installed on the remote computer. Nevertheless, the real power of the application remain inside NDepend so it’s more like a summary report than a tool to use.

The next step is to continue inside NDepend Analysis tool and to use the NDpend Interactive UI Graph.

This give you a snapshot of all dependency your application have. This is a good tool to evaluate the coupling of your projects. Nerd Dinner project is a single DLL and another of testing, the test ain’t useful as if you had a real solution with hundred projects inside it. You can from there go to some matrix views that will give the number of dependency and some more information to go deeper and deeper with all relationship between assembly. I think it can be very useful for project of a decent size to keep control of access. Lowering coupling and increasing cohesion is always a mission and this tool help you to achieve it.

Next, we have the Queries and Rules Explorer. This tool have predefined queries that are in the form of Linq statement. They are queries executed against your code. Not only predefined queries are available, but you can modified them and add new one as you like.

For me, this is THE killer functionality of NDepend. Let’s start with an example. If we choose the category “Code Quality” and select the metric “Methods too bigs” we see in a panel the query itself and the result under it.

As you can see, I know that LogOnPostAssert(string) contain 31 lines of code which generate 205 IL instructions. The query was searching for method with over 30 line of code or 200 IL instructions. Not only that, but NDepend help in embedded with the query panel which let you expand the information with a link to their website. No need to search to know why the query has been made this way, everything is clearly stated. From this screen, it’s possible to double click the method and to see the code that is problematic and to do necessary changes.

NDepend is a great tool to have if you care about code quality and iterative improvement of your application. You can use the tool within few minutes of installation but will require you more hours to truly go deeper in its functionalities.

You can download NDepend and give a try for 14 days free. After this period, the cost is 368$US for 1 seat and go down if you want a bundle of licences. I think every team should have at least one version per team and to periodically do a run to see if the quality go up or down.

DropCreateDatabaseIfModelChanges will create your database every time you start your application


DropCreateDatabaseIfModelChanges is an implementation of IDatabaseInitializer that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created.

That mean that if you are developing something and want to have the database updated to your model changes that you need to create your class that inherit DropCreateDatabaseIfModelChanges . This implementation require you to use the type of the Database Context because it’s a generic class. The class that you will create will inherit from DropCreateDatabaseIfModelChanges.

public class DatabaseContextInitializer : DropCreateDatabaseIfModelChanges<Databa<a href="https://patrickdesjardins.com/blog/dropcreatedatabaseifmodelchanges-will-create-your-database-every-time-you-start-your-application/id-10022565" rel="attachment wp-att-1280"><img src="https://patrickdesjardins.com/blog/wp-content/uploads/2012/08/ID-10022565.jpg" alt="" title="ID-10022565" width="400" height="266" class="aligncenter size-full wp-image-1280" /></a>seContext>
{
    protected override void Seed(DatabaseContext dbContext)
    {
        // seed data
        base.Seed(dbContext);
    }
}

Once created, you need to set the DbContext to know about this Initializer. This is done by setting it inside the OnModelCreating of your DbContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     Database.SetInitializer(new DatabaseContextInitializer());

     base.OnModelCreating(modelBuilder);
}

You can set inside Seed some alter table statement or anything you want to be loaded into the database.

The DropCreateDatabaseIfModelChanges should only be used on the development machine because in production it will cause the suppression of all your real data when the model change.

They are also the implementation called DropCreateDatabaseAlways which will drop every time the context is initialized. This is also only good for development purpose.

What is the goal of using database context initializer?

The goal is to create all your model inside the code and let Entity Framework create for you the database. This is why it’s called “Code First” approach because you work on the classes and let Entity Framework handle the database. Once it’s create, you can remove the statement and deploy.

Understand basic navigation with Entity Framework Code First (4.3) with 1 to 0..1 relationship

Most of the work is done in your DbContext when we talk about configuration of your entities. This is also true for navigation properties that can be set via the fluent interface of Entity Framework.

The first step is to override the method OnModelCreating.

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
   //...
}

From there you can work in two different ways, the first one is to create class for each entity’s configuration. The second one is to work directly into the OnModelCreation method. I prefer the first one because it’s cleaner with bigger project.

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
    modelBuilder.Configurations.Add(new MyEntityConfiguration());
}
//...
public class MyEntityConfiguration: EntityTypeConfiguration<MyEntity> 
{
    public MyEntityConfiguration()
    {
        //Configurations here
    }
}

As you can see, the type inherited by the configuration class is EntityTypeConfiguration but could be ComplexTypeConfiguration for complex type instead of entity type.

To make it shorter, for the purpose of this blog post, I won’t use the classes approach but in real life, I would suggest your to use it.

HasRequired and HasOptional

This two keywords work in conjunction of the use of virtual object inside your classes. They will specify the type of relationship between entities.

HasRequired is implicit if you declare a virtual property for your class. For example, the code below display 2 classes and both of them refer to each of them. This is a 1 to 1 implicit relationship.

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public virtual Profile Profile { get; set; }
}

public class Profile
{
    public int Id { get; set; }
    public string PostalCode { get; set; }
    public virtual User User { get; set; }
}

No configuration is required, nevertheless, you could have wrote in the DbContext some code that explicit the navigation type.

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
    modelBuilder.Entity<User>().HasRequired(t => t.Profile);
}

This scenario is good for the case that a “User” require to have a “Profile” but “Profile” class can be created without being linked to a “User”. If you want to specify if it’s the class “Profile” or user “User” that will contain the relationship than you need to use the clause WithRequiredPrincipal or WithOptionalPrincipal.

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
modelBuilder.Entity<User>()
   .HasRequired(t => t.Profile)
   .WithRequiredPrincipal(t => t.User);
}

The first code that were using HasRequired only was in fact using implicitly “WithOptional(t=>t.User)”. The User would have the relation inside the table and not profile. The second code also specify with WithRequiredPrincipal that the User will hold the foreign key.

Has or With

You have HasRequired, HasOptional, HasMany and HasForeignKey. In the same time you have WithRequired, WithOptional, WithMany. What is the main difference between those method with Has and With. The first one, the Has, represent the navigation property. The second one, the With represent the reverse property configuration. Let say you have class A and class B. If you configure the entity A every call with the keywork Has will be on the class A property (you can see this within the lambda expression that will be of type A with the return of type B. However, if you use property with With in prefix, you will configure B to A relationship. For example :

modelBuilder.Entity<A>().HasRequired(a => a.B).WithOptional(b => b.A);

To clarify even more the Has and With, here is a more complex scenario that involve many classes.

Lets focus on the Car class and the Customer class. In this scenario, a car can have or not a owner (Customer). The customer can have, or hot a current car (Car). This is a circular reference because the current car and the current owner are always the same. They are 3 ways to do it with Entity Framework Code First using Fluent API. The first one is to define the Entity Type Configuration on the Car. The second one is to define the relationship on the Customer Entity Type Configuration. The third possibility is to defined both side. Of course, the last one will require you to have something cohesive between both configuration but has the advantage to be very explicit.

        public class CarConfiguration : EntityTypeConfiguration<Car>
        {
            public CarConfiguration()
            {
                HasOptional(x => x.CurrentOwner).WithOptionalPrincipal(t => t.CurrentCar); //User contain the Customer FK
            }
        }

        public class CustomerConfiguration : EntityTypeConfiguration<Customer>
        {
            public CustomerConfiguration()
            {
                HasKey(x => x.Id);
                HasOptional(x => x.CurrentCar).WithOptionalDependent(t => t.CurrentOwner);//Defined inside the CarConfiguration (up-side-down), may not be required
            }
        }

In the first scenario, we would have only the HasOptional statement on the CarConfiguration class without having anything in the CustomerConfiguration. It’s the reverse for the second way. The last one is exactly the whole code you see above, with both navigation defined.

In the case you think you can only setup the HasOptional on both without setuping up the WithOptionalPrincipal or WithOptionalDependent you are wrong. This will lead to an error :

Unable to determine the principal end of an association between the types ‘EFCodeFirst.Models.Car’ and ‘EFCodeFirst.Models.Customer’. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

How come? Because it’s impossible for Entity Framework to know who’s between the Customer or the Car contain the reference of the object. This is because if one of the object require to have the reference and the other one not, Entity Framework will create the table with the reference on the table with the required FK required. This is why having the code below won’t work and raise the error described.

        public class CarConfiguration : EntityTypeConfiguration<Car>
        {
            public CarConfiguration()
            {
                HasKey(x => x.Id);
                HasOptional(x => x.CurrentOwner); //Error!!!
            }
        }
        public class CustomerConfiguration : EntityTypeConfiguration<Customer>
        {
            public CustomerConfiguration()
            {
                HasKey(x => x.Id);
                HasOptional(x => x.CurrentCar);// Error!!!
            }
        }

The only time you can write HasOptional or HasRequired without defining the other side of the navigation is when you have the class having the reference to the other object and that the other one doesn’t. If we want to do it with our class Car and Customer we just need to remove from Customer the Car property like the following code.

   public class Car:BaseEntity
    {
        public Customer CurrentOwner { get; set; }      //Relationship : One to (zero or one)
    }
    public class Customer:BaseEntity
    {
   
        //public Car CurrentCar { get; set; }                     //Relationship: One to (zero or one)
        public License License { get; set; }                    //Relationship: One to (zero or one)
    }

        public class CarConfiguration : EntityTypeConfiguration<Car>
        {
            public CarConfiguration()
            {
                HasKey(x => x.Id);
  
                HasOptional(x => x.CurrentOwner);
            }
        }
        public class CustomerConfiguration : EntityTypeConfiguration<Customer>
        {
            public CustomerConfiguration()
            {
                //Nothing
            }
        }

This will work.

Conflicting changes to the role X of the relationship Y have been detected.

Entity Framework can be something hard to debug. This error was known by me when people use reference to an object and also an integer for the ID within the same object and change both of them. When this happen, Entity Framework raise an error because it cannot know which one is the correct reference.

public class MyEntity
{
   public virtual MySecondEntity MySecond{get;set;}
   public int MySecondEntityID{get;set;}
}

The code above can trig the error :

Conflicting changes to the role X of the relationship Y have been detected.

To solve this problem, you only need to change the scalar property (integer) and not touching the complex attribute (the property).

But, let say that you have this error without having this kind of structure. Let say you only use reference to the object (like I do).

public class MyEntity
{
   public virtual MySecondEntity MySecond{get;set;}
}

How can I have this error? Well, I had this problem when MyEntity was brand new (ID = 0) and when MySecond also a reference to MyEntity. This is because MySecondEntity has a reference to MyEntity which is ID = 0. Those 2 MyEntity will be treated as 2 differents entity by Entity Framework. The trick to solve this issue is to set to NULL the reference inside MySecondEntity and let Entity Framework set in the database the reference. This can be done because the new MyEntity does have a reference to the MySecondEntity property.

To conclude, if you have a conflicting change and you are using code first with property reference, be sure that when you insert a new entity that not both reference to an entity with a new ID. Just one part of the navigation require to be defined.

TempData why you should use bracket instead of .Add

TempDataDictionary (TempData is of type of TempDataDictionary) is useful if you need to keep you data between redirection. I have see some case of error with programmer who use the TempData with the Add method.

First the Add method won’t let you add more than 1 same key. This mean that it will crash if you write:

TempData.Add("key1","value1");
TempData.Add("key1","value2");

You will tell me why someone will do this, well, in the scenario of redirection, which should occur if you are using TempData instead of ViewBag you may comeback in the same path of code that the user set the data. In this case, the value are set twice cause the TempData in a redirection keep its values.

So, you can add some validation with the ContainsKey method.

if(!TempData.ContainsKey("key1"))
{
    TempData.Add("key1","value1");
}

Second, this solve the problem but create overwhelming code for a simple task. The solution in my opinion is to simply use the bracket overload of the TempDataDictionary.

TempData["key1"] = "value1";

The code is shorter, cleaner and do what we want. It set the value and if it’s a redirection to the same code who has set the value this one will just reset the same value. That’s it! Simple and clean.

If you are curious about the bracket code, here is the source code of the TempData for the property [].

private Dictionary<string, object> _data;
private HashSet<string> _initialKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
//...
public object this[string key] 
{ 
    get 
    { 
         object value;
         if (TryGetValue(key, out value)) 
         { 
             _initialKeys.Remove(key);
             return value;
         }
         return null; 
    }
    set 
    { 
        _data[key] = value; 
        _initialKeys.Add(key);
    } 
}

Of course, the real question now is why does this code has redirection that double set this value, but this is another story.

Make all actions of controller securized with Authorise filter implicit

Few months ago, I had to Asp.Net membership to an Asp.Net Mvc project. Instead of adding the filter [Authorize] on every action that require to have a valid authentification I decided to use the technic describe in this MSDN Blog.

The main goal is by inverting the normal behavior of the security, which is to mark with a filter which method to protect, is to mark the one that shouldn’t be protected. That mean that by default, everything is secured. By default, everything require an authenticated user. So, with this new filter, only anonymous method require to have the filter.

How do we implement that? First, we need to add a new filter that will authorize only method that contain a specific filter. This is done by adding 3 line of code in the Global.asax.cs.

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
    filters.Add(new LogonAuthorize());
}

Since version 3 of ASP.NET MVC, you can add the AuthorizeAttribute filter to the global.asax file to protect every action method of every controller. Second, we need to create the LogonAuthorize class that inherit from AuthorizeAttribute.

 public sealed class LogonAuthorize : AuthorizeAttribute {
        public override void OnAuthorization(AuthorizationContext filterContext) {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            if (!skipAuthorization) {
                base.OnAuthorization(filterContext);
            }
        }
    }

If the base.OnAuthorization() is skip, than we do not have any protection. If the base.OnAuthorization() is called, than the protection mechanism is called and authentification rules are applied.

So, what’s happen in the OnAuthorization method? It simply check if the method or the class contain the attribute defined (AllowAnonymous). If it does, than we skip the authorization so we do not call the base class (AuthorizeAttribute).

From there, you need to add [AllowAnonymous] to methods that you want to be allowed without having the visitor authenticated. For example, method for login and creating an account should have this attribute.

 [AllowAnonymous]
 public ActionResult LogOn() 
 {
    //...
 }