Using AutoMapper with Entity Framework between to EDMX Containers

If you try to map two EF Models with AutoMapper, you’ll run into an issue when persisting. At runtime, EF add a base EF object to the model. AutoMapper maps these properties. If the mapping is between two models from the same context, then it’s not an issue. The values are the same. If the models live in different edmx containers and issue arises. The EntityState and EntityKey values are also mapped.

Automapper does not have the means to ignore inherited properties. This leaves a problem. How does one map EF models between edmx containers?

To solve this issue, I created a small extension method:

public static class AutoMapperExtension
    /// <summary>
    /// Ignores the definition properties for EF models.
    /// </summary>
    /// <typeparam name="S"></typeparam>
    /// <typeparam name="D"></typeparam>
    /// <param name="expression">The expression.</param>
    /// <returns>IMappingExpression{``0``1}.</returns>
    public static IMappingExpression<S, D> IgnoreEFProperties<S, D>(this IMappingExpression<S, D> expression)
        expression.ForMember("EntityKey", o => o.Ignore())
            .ForMember("EntityState", p => p.Ignore());
        return expression;

When to Add a Project to a Solution

To my knowledge there is not an official standard on when to add projects to a solution.

As a software consultant I’ve seen it done many ways. Below are the most common approaches to project structures.

By Namespace

One school of thought is each namespace gets a project. In most cases the projects don’t have any sub folders. This structure allows for simple project layouts. The downside is it can lead to solutions with 40, 50 or more projects.

By Separation of Concern (SOC)

Another school of thought is by SOC, for example a project for the UI layer, a project for the model (entities), a project the business logic and a project for the data layer. This allows for easy identification of the logical layers. The downside is SOC has nothing to do with assemblies. Just because the projects and the logic layers can be aligned does not mean they should.

Minimalist Approach

This school of thought keeps everything together until there is a reason to split it out. Reasons you’d want to split out code could be for testing or for using the code in another project.

In its extreme you’d have one project with the models and the data access together. The code would logically be broken up. SOP would be enforced by the architecture, not the project structure. The upside to this approach is the project structure is simple. You’ll have 2 to 4 projects in a solution. The downside is that it’s the responsibility of the developer to enforce SOP.

Which approach do I use?

I follow the Minimalist Approach.  Identifying SOC is hard. The Minimalist approach is not for the faint of heart. Those whom don’t have a concrete grasp on SOC will be better served aligning SOC and the project structure. This ensures there will be no cyclical references and SOC.

Clustered Index and Non-Clustered Index

Clustered Index
Clustered Indexes are primary keys and uniquely identify the data, they are called clustered index because the data is clustered together on the file-system. Clustering the data allows for quick retrieval and a table can only have one clustered index.

Non-Clustered Index
A non clustered index is an index that points to the clustered index. Ideally, the data has limited duplication. For example, take a create date. Rows created on a specific data has a limited scope of that day. Creating a non clustered index on CreateDate will allow quick retrieval of rows grouped by CreateDate. Thing of it as a grouping of all the same data with a reference(clustered index) to the physical row.

Nothing is free, the benefit of creating indexes is speed. Read speed greatly increases. The cost is insert, update and deletes slow down.

Fail Fast

For goodness sakes don’t swallow exceptions! It’ll kill you (not really)!!!

Don’t try to hobble along. If an exception is thrown, log it, present the user with a “Sorry, but we had a problem…” message and assure them you are on top of the issue and graceful close the application or restart it.

In business programming there is no reason to try to “Save” the context. It’s a disaster waiting to happen. By swallowing an exception the application is put into an unknown state. Badness can happen when your application is an unexpected state. Anything from data corruption to your application being compromised. One of the strategies of hackers is to test edge cases, looking for an in or an error to gain more information on compromising the application.

When your application throws an exception, logged it and close the application. The context may have been lost, but the application lives on.

The Three Tenets of Object Oriented Design

The three principles of Object Oriented Design.


Polymorphism – Is the ability of an object to have more than one form.

Inheritance – Is the ability for an object to be sub classed from a base or parent class. Typically the child classes share some common functionality with the parent class.

Encapsulation – This is simply the hiding of implementation or data. “Don’t be concerned on how it’s done…”

Am I Due a Raise When I Graduate?

I’d like to give the company the benefit of the doubt, but in my experience they don’t deserve it. They probably hired you at lower rate to get a steal. Remember, all businesses are in the game to make a profit otherwise they die, which is bad for you. At the same time, if you leave the company, they also loose. They have hiring costs and training costs invested in you and you have part of the company mind-share. They do not want to loose their investment in you.

If I was hiring you, I would bring you in as low as possible. Let’s say at 50k. If this your first professional job, you are probably use to making 10 to 15 dollars an hour. That is roughly 30k a year. They offer you 50k a year. That seems like a lot of money to you and you accept.

You graduate with a degree, yes you are worth more, but we started you out at 50k. We’ll give you a 10 percent raise. They will give you some line of crap about how a 10 percent raise is almost unheard of in the industry and it’s tough times! You can tell them it’s not enough and explain to them the average wage is 65k for your position and that you’ll cut them a deal and accept 70k. Because that’s how good you are. Or you can do what most people do and accept the 10 percent wage and feel all warm and fuzzy inside.

Are you willing to find another job? Your bargaining chip is you leaving. I’ve seen people ask for a raise and not get it. They leave company and come back a year later taking a higher position and making double their old salary.

WordPress 3.5.1 MultiSites on Windows Azure

Out of the box the web.config included does not work with sub-directories.

The following web.config worked for me on Windows Azure:

<?xml version="1.0" encoding="UTF-8"?>
        <rule name="WordPress Rule 1" stopProcessing="true">
          <match url="^index.php$" ignoreCase="false" />
          <action type="None" />
        <rule name="WordPress Rule 2" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?files/(.+)" ignoreCase="false" />
          <action type="Rewrite" url="wp-includes/ms-files.php?file={R:2}" appendQueryString="false" />
        <rule name="WordPress Rule 3" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?wp-admin$" ignoreCase="false" />
          <action type="Redirect" url="{R:1}wp-admin/" redirectType="Permanent" />
        <rule name="WordPress Rule 4" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions logicalGrouping="MatchAny">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
          <action type="None" />
        <rule name="WordPress Rule 5" stopProcessing="true">
          <match url="^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*)" ignoreCase="false" />
          <action type="Rewrite" url="{R:1}" />
        <rule name="WordPress Rule 6" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?(.*.php)$" ignoreCase="false" />
          <action type="Rewrite" url="{R:2}" />
        <rule name="WordPress Rule 7" stopProcessing="true">
          <match url="." ignoreCase="false" />
          <action type="Rewrite" url="index.php" />

Comparing Enums With the Same Values

comparing_notes_popupRecently I came across some code where a switch statement was used to convert one Enum to another Enum. There were over 20 cases in the switch statement. The kicker was the values were the same. Why did they not use a single Enum? I’m still trying to figure that out.

I wrote some code that eliminated the massive switch statement:

        public TTo MapEnum(TFrom from)
            where TFrom : struct, IConvertible
            where TTo : struct, IConvertible
            System.Diagnostics.Contracts.Contract.Requires(!typeof(TTo).IsEnum, "TTo must be an enumerated type");
            System.Diagnostics.Contracts.Contract.Requires(!typeof(TFrom).IsEnum, "TFrom must be an enumerated type");
            string fromValue = Convert.ToString(from);

            TTo toEnum;
            bool found = Enum.TryParse(fromValue, true, out toEnum);

            if (!found)
                throw new Exception("Could not find value {0} for type {1} in enum {2} ");

            return toEnum;

Writing the SVN Reversion to a File in TeamCity

I spent hours trying to figure this one out. It turned out brain dead simple.

  1. Add a build step
  2. Select the command line runner type
  3. Set the working path to the path you’d like to save the version file too.
  4. In the Custom Script Text Field add the following text: ECHO %build.vcs.number% > version.txt