Allow Me To Share My Toolset Choices for Developing On .NET

There was a question in a tech facebook group I co-manage about what tools you’d use if starting a new project today.


I don’t know for sure. It depends -of course- is the expected answer. For example, there’s some idea I had I mind I considered using MongoDB or CouchDB for, while still using .NET, and then I wasn’t sure if I go extra mile in DB I’d go for Node or Rails as well or would prefer .NET for my personal productivity. I also often use Node/Bower when checking libraries with many dependencies.

So, for this question, I thought what tools I might use in a company project. Thinking back, I found that most tools I use now are good enough for what they do. So, I thought I’d list these.

These tools are my personal experience though. While some of them are widely adopted in Readify, some others may have been specific to some clients or Readify teams I worked with. Every team is free to choose the tools that work best for them and make it easier to deliver high quality deliverables in sensible time, so, even if you are at Readify, your mileage may vary…

The Tools

Server Side Web


  • SQL Server (or SQL Azure, although I don’t like SQL Azure, because it’s not compatible with some scripts generated from SSMS, which I sometimes use to generate migration scripts)

  • DbUp for DB migrations (there are some other nice options now)

  • Special SQL views + Web API OData + MS Excel for reporting

Client Side Web

  • Angular.JS on the client when I have the choice, Knockout.JS and jQuery UI (being deprecated now) at some big client I keep going back to every few gigs

  • LESS for CSS, or SASS (SCSS) when the CSS is handled by one of our favourite design agencies

  • Chrome devtools for web debugging (obviously), unless it’s IE issue of course.


  • Phonegap (most just the open source part of it, Cordova) and Ratchet CSS framework (considering alternatives, like TopCoat) for mobile development, with Angular.JS

  • Considering Xamarin as their work seems to be VERY cool, and I recently get access to their stuff via my company (OT: Also considering Neo4j DB for similar reasons).

IDEs and Text Editors



Internal Communication

  • Several kinds of wikis used by different clients, often with OneNote

  • HipChat for team communication, sometimes Skype and/or Lync as well

  • AnswerHub (Stackoverflow clone) for internal questions forum where I can safely quote client sensitive information in my question

  • Yammer for internal company social network

How about you?

What tools do you you use when developing?

Let me know in the comments, via email, or on twitter!

Enforcing ASP.NET MVC Conventions With Unit Tests, Or Solving The AJAX HTML Redirect To Login Page Problem

This blog post is about an ASP.NET MVC workaround we implemented in a previous project. We solved the problem by enforcing using a class that extends one of ASP.NET MVC classes, which in itself created another problem, as new developers joining the project may always use the old class. The solution to this problem was not something that I invented, but it’s also not a very common practice.

So, if you are interested, here’s the entire story…

Detecting Session Timeout In AJAX Requests

We wanted to solve a problem where in an AJAX heavy ASP.NET MVC application, if the user triggers an AJAX action after staying inactive for longer than our application timeout, the call to the controller action, which normally gets a JSON response, would instead get the HTML of the login page.

This is a known issue in ASP.NET (particularly System.Web). A feature that’s on by default is returning a redirect to the login page instead of a HTTP Unauthorized Status code (401). After the redirect the response returned is a successful (HTTP Status Code 200) load of the login page. That means even our Angular.JS error interceptors (or jQuery handlers, etc.) don’t notice there was an error.

A fix for this was turning this feature off. We inherited the Authorize attribute as below:

 /// <summary>
 /// Suppresses Forms Authentication Redirects for Ajax requests 
 ///     so the client side interceptors can handle it.
 /// </summary>
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, 
     Inherited = true, AllowMultiple = true)]
 public class AuthorizeRedirectAttribute : AuthorizeAttribute
     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
         var context = filterContext.HttpContext;
         if (context.Request.IsAjaxRequest())
             context.Response.SuppressFormsAuthenticationRedirect = true;


SuppressFormsAuthenticationRedirect is the property that disables the login redirect. Microsoft set it to false by default so that it’s backwards compatible.

ASP.NET MVC doesn’t recognize AJAX requests through Request.IsAjaxRequest() via Accept header or so. It does via checking X-Requested-With header. Most AJAX-capable frameworks like jQuery and others offer a way to intercept all requests and add extra headers, for example, in that app, we configure Angular.JS to include the header with some code similar to this:

 app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

Enforcing The Convention

The obvious problem with the previous solution is that we are ignoring The Power Of Defaults. Any other developer who may join the project needs to know that using Authorize is a no-no, and even for old devs (myself included),
it’s very easy to just forget and use Authorize not AuthorizeRedirect just out of habit.

Solving this problem was quite easy though, we added the following test to our Unit Tests project:

 public class AuthorizeRedirectTests
     public void All_Controllers_And_Actions_Do_Not_Inherit_Authorize_Directly()
         var controllerType = typeof(IController);
         var invalidAuthorizeFilter = typeof(AuthorizeAttribute);
         var correctAuthorizeFilter = typeof (AuthorizeRedirectAttribute);

         var webProjectAssembly = correctAuthorizeFilter.Assembly;
         var controllers = webProjectAssembly

         Func<MemberInfo, IEnumerable<object>>
             invalidAttributes = member =>
                     // Note that AuthorizeRedirectAttribute inherits from AuthorizeAttribute

         foreach (var controller in controllers)
                 "Controller {0} should not use {1} directly, " +
                 "use {2} instead",
                 invalidAuthorizeFilter.Name, correctAuthorizeFilter.Name);

             var actions = controller
                 // Simple check, might get some false positives but they won't hurt
                 .GetMethods(BindingFlags.Instance | BindingFlags.Public);

             foreach (var action in actions)
                     "Controller Action {0}.{1} should not use {2} directly, " +
                     "use {3} instead",
                     controller.Name, action.Name,
                     invalidAuthorizeFilter.Name, correctAuthorizeFilter.Name);

I hope the code is self explanatory. We check the web project assembly for all ASP.NET MVC Controllers, then we check the Controllers and all their Action methods for existence of the AuthorizeAttribute. We filter those that use the correct attribute (AuthorizeRedirectAttribute), and we Assert that there are no the no Controllers or action remaining, otherwise, we tell the developer which Controller or Action needs to be fixed, and how to fix it as well.

Room For Improvement

The drawback of this is that our Unit Test project had to reference the ASP.NET MVC assemblies and gets more stuff than most tests should need. We can overcome this by moving our “convention” tests into another project completely, but for this project the conventions were very few and it seemed fine.

Of course the same method can be applied to any other convention you enforce in your project. One obvious example is ensuring all Controllers inherit from a custom base Controller class instead of the ASP.NET MVC class directly. I know people who already do this, as I mentioned in the opening the technique is not new by any means, but it’s worth even more popularity.

Speaking of improvement, the code for this test class was optimized a bit while writing this blog post, there is always room for improvement :)


In case you were reading the code carefully, the IsNullOrEmpty() method I used in assertions is a custom extension method we had in the project, a very simple one as you may expect:

 public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
     return source == null || !source.Any();

And That’s it!

I hope you found the technique useful if you haven’t used it before, or found the post a good place to reference it to those who didn’t.

Using Visual Studio Developer Command Prompt With PowerShell

Running Developer Command Prompt for Visual Studio

The Visual Studio developer command VsDevCmd.bat only works with the cmd.exe command line shell/processor, which is still the native command prompt in Windows. Try writing some command in Start->Run or Explorer’s address bar, and you’ll find that you need to use the cmd/batch command syntax (for example, using %SOME_NAME% syntax for variables).

What if you want to us VsDevCmd.bat? You want the stuff it adds temporarily to the PATH and all the other goodies it brings, but prefer to work in Powershell?

Using VsDevCmd With PowerShell

You can try to run VsDevCmd.bat from PowerShell, but this will execute another command prompt shell on top of it.

However, you can also easily do the opposite. Run the VsDevCmd.bat, and from the command prompt, just type PowerShell and press ENTER. The new Powershell session will inherit all the fluff that VsDevCmd.bat added to the command prompt session.

A Quick Shortcut

You can always have a simple shortcut to load VsDevCmd.bat with Powershell instead of writing everytime.

Simply create a new text file, and enter the following in it:

<code>cmd.exe /k ""%VS120COMNTOOLS%VsDevCmd.bat" & powershell" 

Save the file and change its extension to .bat. When you run it, it will run the command prompt and keep it open, run VsDevCmd.bat, and then powershell.

You can test it by running, ensuring the prompt shows the PS > prompt for PowerShell, then run msbuild to ensure it was added to the PATH by DevCmd.bat.

Using By Default, ConEmu

On my personal machine, I use ConEmu as my all-time console environment. If you don’t know about it, Scott Hanselman described it in depth.

Among many other things, ConEmu allows you to create tasks that can be executed by default when you open a new console tab. This allows you to have for example some preset (task) for sat Bash/cygwin, another for cmd.exe, another for PowerShell, etc. Maybe even another task that loads some extra variables or whatever that you don’t want always attached, but still want them handy when you use the console. It also allows you to optionally choose one task to be the default when you open ConEmu.

So, for me, the task I set to be the default in ConEmu is the following:

<code>* > cmd.exe /k ""%VS120COMNTOOLS%VsDevCmd.bat" & powershell" -new_console:d:D:\Some_Folder

the first * > bits are ConEmu specific, telling it to run task as admin and make it active tab (if you can set multiple tabs in the same task). And the -new_console: switch allows passing other parameters to ConEmu when starting, like d:D:_data, which sets the start-up directory to a prefered directory I have. The rest in the middle is the simple command which calls VsDevCmd.bat and then starts PowerShell.


How to set the initial value of a select element using AngularJS ng-options & track by

I have been doing Angular.JS in production projects for months, that it did surprise me recently how I haven’t used drop-downs in it. Well, I mean how I haven’t used them enough to get into several problems I had in my current project, and other friends at the same office had in their project as well.

To save you the pain I went through, I’ll list some problems and solutions here, and then give you a video that shows going through all of them ans the thought process that led to the solutions.

Initial selection

<code><select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in objectList ">

Assuming someObject in the model has the same properties and values as someObject in the objectList, it will still not be selected.

It’ll only be selected if someObject was actually one of the objects in objectList, like objectList[0] or whatever. Otherwise, Angular.JS will insert an empty option tag with no value or text and select that.

Root Cause

Angular.JS uses native JavaScript comparison for comparing the objects. In JavaScript, unrelated to Angular.JS or anything, comparing objects (object literals) is “by reference”, so it doesn’t factor the similarity of the objects. Only checks if the two references compared point to the same object in memory or not.


An un-documented (AFAIK) feature in ng-options is that you can use some bits from the ng-repeat directive with it, like track by. This allows us to choose some property as the comparison key.

<code><select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in objectList track by someObject.key">

If the key property is a simple type, like Number or string, JavaScript will consider it equal to any other object that has the same value, so we don’t have to use the same objects.

Invalid Value Sent On Server-Side Submit

When Angular.JS writes the <option> tags from an ng-options directive pointing to an array, the value of the option is always the index of the element it maps to in the array. This is not important if you process the selection on client side because you only deal with the result of ng-model anyway, you can use this later to create an AJAX request or whatever.

However, if you intend to submit the form using a normal server submission, and only use Angular.JS for say validation or managing complex form interaction (client-side tables containing sub-items with add/remove/sort for example), this may be a road blocker to using Angular.

Root Cause

By default Angular.JS uses the index of the array to track which object maps to which <option> element.


Similar to the previous problem, use the track by syntax. Angular.JS will use the track by property value as the <option>‘s value. Most of the time your tracked property is the key property you want to send to the server anyway, so, this should be good enough.

Simple Properties Scenario When Combined With Server-Side Submit

Let’s say you want something as simple as this:

    ng-options=" as gender.text for gender in genders">

This syntax will work very well, if you only use this value from JavaScript, you are all set. But if you plan to send it directly to the server (a normal non-AJAX form submit), you’ll want to consider using the track by syntax, like track by

However, if you do this, you’ll notice that the select is no longer usable. No initial selection, and changing selection although updates the model, it does not show the new selected value.

Root Cause

The track by syntax expects an object, with the property you use to track. It does not honor the key part used in the key as text syntax (which in our example is as g.text), so, it wants the ng-model to point to an object with the tracked property, it cannot be the key itself directly.


I didn’t call this a solution, because it’s pretty much a hack.

    ng-init="person._gender = {id: person.genderId}"
    ng-change="person.genderId ="
    ng-options=" as gender.text 
        for gender in genders track by">

We created a new property (which I liked to prefix with _ to show it doesn’t normally belong to the model object), initialized it to a new object that contains only our key property id set to the original simple value genderId, and then used that as the model (as in ng-model).

We created and assigned the property in ng-init, then synchronized the changes to the simple property via ng-change. This allows the code everywhere else in the application (like the controller, or other parts of the markup) to only interact with the property we want (genderId in this example), without knowing about our hack. This makes things a bit cleaner, although it still remains a hack rather than a solution.

You can view an example of using this hack here.

Adding extra selection items to the dropdown

One thing you notice if you are affected by the “initial selection” problem, is that the empty <option> tag that Angular.JS adds when it can’t match the ng-model to the array from ng-options disappears when the use changes their selection. We have gone through how to avoid showing the empty option by mistake already.

But if you do want to have that option, it’s easy, just, um, add it!

<code><select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in 
        objectList track by someObject.key">
    <option value="">-- Select an option--</option>


If you are using Angular 1.4+, check the much smaller 2nd part of this article, about how to use track by correctly.
Using track by correctly with Angular 1.4 select ng-options – Why can’t I select this option?

The Video

If you want to dig these problems really deep and see what they look like in action, and what was the thought process for solving them like and in some cases other possible solutions, I have put all this in a (rather long) video here:

Serializing A PagedList Using JSON.NET In ASP.NET MVC – Gotcha And Workaround

Recently I discovered that there’s no one standard way for AJAX-driven server-side paging in ASP.NET MVC (in Web API, you can expose an IQueryable). For the case in hand, I decided to use PagedList for the server bit of the game.


The PagedList interface looks a bit like this (for demonstration only, real code is a bit different, check its source code for the real stuff):

It provides nice properties for paging, and exposes itself as enumerable and has an indexer. Apart from this snippet, the library also provides an extension method ToPagedList() to apply to any enumerable and allow it to populate the properties from it (by enumerating on it, and by calling the Count() method).

We were also using JSON.NET for JavaScript serialization, which is pretty much defacto standard nowadays.

The JSON.NET Serialization Problem

JSON.NET has a nice implementation, if you serialize a class that implements IEnumerable<T>, and you don’t have a special treatment rule for it (via what JSON.NET calls “Converter” classes), when you serialize an instance of the class to JavaScript, it will be serialized as a JavaScript array, where the enumerated objects are the contents of this array. Makes lots of sense right?

Well, yes, except when you have a custom collection like PagedList, and you want to treat it as an object that has several properties, not as an array. JSON.NET does provide a solution for this actually, all you need to do is apply the [JsonObject] attribute to your class.

Unless you don’t own the source code of this class.

In this case, you need to inherit from it. By doing this, I lose the nice ToPagedList() extention method (because it creates an object of the PagedList class directly), but luckily it does nothing but calling new PagedList() with the parameters we give it, so, we don’t lose much.

Here’s how my implementation looks like:

Apart from having to copy the constructors to pass parameters to the base ones, have you noticed the extra Items property in there?

That’s because the Subset member it includes is actually a field, not a property, and JSON.NET won’t serialize that by default, I could override it somewhere else, but since I’m fiddling with this here, it made sense to just stick a property to the class.

Bonus: A Bit More On Implementation

In my actual code, I have added the Dynamic Linq NuGet package, and assumed a single property for sorting (which was fair for the situations where I intend to use this), so, I complemented the code above with another class that looks like this:

This allows the controller to instantiate an instance of the SerializablePagedList class, pass it all the way to whatever repository method I have.

The repository method will take it as a parameter, work out what IQueryable it needs, and instead of passing it to UI, it calls CreatePagedListFromQueryable(), which returns an innocent-looking PagedList object (because SerializablePagedList inherits PagedList) that the repository can pass back to the controller, which can serialize it to JavaScript without a problem, then the rest is all JavaScript code to work out how create the paging parameters, and how to use the returned paging hints.

Even more, now that I think about it, maybe I should change the return type to SerializablePagedList, to make the Items property visible to the developer (because they’d think it’s magic, and in coding, magic is BAD). I’ll leave this as an exercise for you :)

Final Words / Disclaimer

The motivation behind this post is that I found the problem of serializing PagedList using JSON.NET a challenge and I wanted to help others work it out faster than I did. Is this how I’d recommend doing paging? Well, I don’t know, but if it’s what you choose, I hope that I have saved you some time.

And more importantly, is it good enough to be the defacto standard I mentioned I was after in the beginning of the post? Not really. I think it’s not bad, but definitely not the best. I’d love to see less clever (read: hacky), and more simpler solutions.

My Quest To Find The Best NodeJS Http Client With HTTPS and Basic Auth

This may be a completely useless post, but it took me a bit to figure out some of the pieces until I got here, so, I thought maybe it’s worth sharing!

What’s this & how did I come by it?

Instapaper is a nice service that provides you with “read it later” bookmarklet. You use this bookmarklet to add any web page to their log and you can read that page later via their site, a mobile application (from them or 3rd party), or via Kindle (or other book readers)!

Apart from their bookmarklet, they provide a simple API to add URLs programmatically. This is useful if you for example want to extract URLs from other services, say twitter favourites. They also provide a Full API (OAuth API) for doing everything their site and apps do, except some things in this so called Full API are (at least to be) only for paid subscribers.


Instapaper’s simple API is quite interesting though, according to the docs, you can use HTTP and provide only username (email) -not even password- to add a URL, and you can use POST or GET. That’s scary for anyone who thinks about security, but -maybe- OK for what the API does. They also provide the API in proper HTTPS with basic HTTP authentication (and if you want more, you can always use the Full API’s OAuth).

I wanted to use their API in HTTPS using POST and Basic Authentication. In my tests I was happy to try HTTP and/or GET and/or sending username in clear-text. I also thought I’d write this in Node because I thought it should be easy. Node people often serve REST/HTTP APIs, so, they must be good at consuming them too (even though in reality most consumers are client JS not node), right? Well, maybe yes.

The Code

I can explain the challenges, how I overcame them, and then show the final code, but I have spoken too much already, let’s begin with the code.

var basicAuthenticationParams = {
username: ‘MY_EMAIL’,
password: ‘MY_PASSWORD’

var requestParams = {
url: ‘’
};“”, {
form: requestParams,
auth: basicAuthenticationParams
function (error, response, body) {
// This is only returned for network errors, not server errors
if (!!error) {
console.log(“Network Error:”);
throw error; // it’s actual JS Error object not string

var statusCode = !!response ?
parseInt(response.statusCode, 10) || null
: null;
// I could have checked for 200,
// but technically 200-299 are success codes,
// and more importantly, Instapaper sends 201 for success
if (!!statusCode && statusCode >= 200 && statusCode < 300) {
console.log(); // Extra line separator

console.log(“HTTP Status:”);
console.log(); // Extra line separator

// In instapaper’s case, by default,
// they just send status code in body too


See? It was all very straight forward. Well, it wasn’t for me. I tried several NPM packages to get this effect, and none was going well. The “request” package was the one that did the trick. this is generally accepted in Node, the built-in API is very low level and there is some NPM package that gives you the nicer one.

For all the other packages I tried, they didn’t have any dependencies on other packages. This “request” package gave me the usual shock seeing so many NPM packages downloaded and installed, but this is the philosophy of NPM, build small reusable pieces built on top of other pieces.

Getting the request headers right (Oh my!)

While the packages were not working, interchanging HTTP status codes between 403 (invalid credentials) and 400 (missing parameters), it was very hard to tell what I needed. Even associating to proxy to get the output to Fiddler didn’t go well with for example the “easyHttp” package (there is a similarly-named NuGet package for .NET BTW, but it’s not related at all I think).

I went to my favourite Chrome Postman extension, which works nicely like Fiddler for the “compose request” part (actually, arguably is even way easier). The request parameters (was using username as another request parameter, not using Basic Authentication, just to test) didn’t seem to work until I changed the default “form-data” to “x-www-form-urlencoded”


Which added the following header to the request: “Content-Type: application/x-www-form-urlencoded”. This kind of makes sense. This overly permissive API feels more optimized for sending from web-pages, where forms are a front concept.

I tried to add the header when I was using other packages but that didn’t seem to tick it. I tried this one, and as you can see didn’t even need to set that. I just used the “form” property of the options though instead of “body” or “”json” properties.

This is why I’m posting this, to hopefully help someone googling get up and running quicker than me. This is not just Instapaper, this can be very helpful in so many situations.

For the rest of you (.NET / non NodeJS devs)…

If you are not a Node person but still want to have a fiddle, after you install Node (which includes NPM package manager by default), then you save the code to a JS file “some-file.js”, preferably in a new folder.

Assuming Node and NPM are in the PATH (installer default), you can open Cmd or PowerShell console in that folder and run npm install request then node some-file.js (no quotes in both), and see the results in front of you.

Twitter OAuth, Persistent OAuth, TweetSharp: Presentation & Code Nuggets

This is a PowerPoint Presentation (and extraction of the contents) I made as per a couple of friends’ request (@EmadAshi and @AmrEldib) to show how OAuth works along with Twitter and how easy it is to cache OAuth credentials.

As I was doing related work for TweetToEmail. I felt a PowerPoint presentation will be even better than a blog post for this one, but here you get the two.

The Presentation

The Contents

Application Registration

  • A Twitter user creates a Twitter Application
    • If the application is web based, it needs to provide a URL. “Localhost” is not accepted as a domain for this URL
  • A Twitter Application gets two pieces of information
  • Consumer Key
  • Consumer Secret
  • A Twitter Application will use these in all coming requests.

Initializing The Process

  • User comes to the application and it decides to authenticate against Twitter
  • Application makes a request using Consumer Key and Secret to obtain “Oauth Request Token”, which consists of two parts
    • Token
    • Token Secret
  • Application makes authentication URL including the “Oauth Request Token” parameter, and optionally a “Call-back URL” (if different than default URL in first step)

User Authentication

  • The user is redirected to Twitter, the URL contains the “Oauth Request” to identify application authentication session
  • Assuming the Twitter User being logged in and authorizes the Application
    • If the application is a desktop application, Twitter gives the a user a number “Verifier” to manually write back to the application
    • If the application is a web application, the user is redirected back to the application call-back URL with a complex “Verifier” parameter in the URL

Obtaining the Access Token

  • The Application makes a request to Twitter including the “Oauth Request Token” and the “Verifier”
  • It obtains an “Access Token”, likewise it consists of two-parts:
    • Token
    • Token Secret
  • The application needs to send the Consumer Key and Secret and Access Token in every future request that needs the Twitter User privileges

Caching Credentials

  • The application needs at least one authorization process as before
  • The Access Token returned can be saved in session/DB/whatever and then re-used later
  • The application can later use the Access Token directly along with the Consumer Key / Secret to communicate with Twitter without going through any of the previous steps

Sample Code (TweetSharp v 2.0)

Request Token & Redirect


Getting Access Token


Hints for Web Applications

  • The method GetAuthenticationUrl() has an overload that accepts a call-back URL for the user to be redirected to after obtaining verifer
  • The important part in RequestToken is the Token part, not the secret.
  • All parts of AccessToken are important and required
  • When the user is redirected back from Twitter to your application, you get the following QueryString parameters sent to you
    • oauth_token: The Token part of the Request Token
    • oauth_verifier: The verifier required to obtain the Access Token later

Using Cached Access Token


Related Links

Typed Eager Loading Using Entity Framework (& What is Eager Loading vs Deferred Loading)

If you don’t know what eager loading is, Jump to “What’s eager loading?”.

Eager Loading Syntax

If you are eager loading Products for example in a typical (Categories 1<->* Products) relation, the standard syntax would like:


What is the problem with that?

The “Products” part. The word “Products” is a string. If I rename the Products table to ShopProducts or whatever or even remove it from this data diagram and have it elsewhere, or even something wrong happens and the relation is removed from DB/diagram by mistake, my code will still compile, but will fail when it runs. This is BAD BAD BAD.

How to solve this?

Since I always believe that if something exists somewhere you shouldn’t do it yourself unless its totally broken (and I mean REALLY REALLY BROKEN), I started searching inside the Entity Framework itself for something to get the entity name from.

At first it seemed super easy. Every entity class has a static property “EntityKeyPropertyName”, so, I thought I can write something like:

DbDataContext.Categories.Include(Product.EntityKeyPropertyName); // But this didn’t work

Where Product is the entity class generated for table “Products”. Note that singularizing the name (Products becomes Product) does not happen automatically like in Linq-To Sql, you’ll have to change it manually, which is not required for the code here of course.

As you an see n the comment, this didn’t work. The value of property was always “-EntityKey-”, the default value of the abstract class “StructuralObject” which all entity classes inherit.

I kept searching all over until I found that the only place I can get the name from was an Attribute generated on the class somewhat like this:

[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName=”DatabaseNameFlowModel”, Name=”Products”)]

My requirement was simple. if the diagram has something wrong that the relation between ParentTable and ChildTable tables but not about the entity classes themselves, My code should not still compile and fail on run. I need to use some code that depends on the relation so that if something is wrong with the relation this code fails early and I know about it the problem the next time I build the VS project.

The Final Solution

I tried badly to get the entity name from the API, after frustration, I ended up writing this code:

<span class="cb1">using</span> System;

<span class="cb1">using</span> System<span class="cb2">.</span>Collections<span class="cb2">.</span>Generic;

<span class="cb1">using</span> System<span class="cb2">.</span>Data<span class="cb2">.</span>Objects;

<span class="cb1">using</span> System<span class="cb2">.</span>Data<span class="cb2">.</span>Objects<span class="cb2">.</span>DataClasses;

<span class="cb1">using</span> System<span class="cb2">.</span>Linq<span class="cb2">.</span>Expressions;

<span class="cb1">using</span> System<span class="cb2">.</span>Reflection;

<span class="cb1">namespace</span> Meligy<span class="cb2">.</span>Samples<span class="cb2">.</span>EntityFramework


    <span class="cb1">public</span> <span class="cb1">static</span> <span class="cb1">class</span> <span class="cb3">LinqExenstions</span>


        <span class="cb4">//Used for child entities.</span>

        <span class="cb4">//Example: Order.Customer</span>

        <span class="cb1">public</span> <span class="cb1">static</span> <span class="cb3">ObjectQuery</span><span class="cb2"><</span>T<span class="cb2">></span> Include<span class="cb2"><</span>T<span class="cb2">></span>(<span class="cb1">this</span> <span class="cb3">ObjectQuery</span><span class="cb2"><</span>T<span class="cb2">></span> parent,

                                                <span class="cb3">Expression</span><span class="cb2"><</span><span class="cb5">Func</span><span class="cb2"><</span>T, <span class="cb3">StructuralObject</span><span class="cb2">>></span> expression)

            <span class="cb1">where</span> T : <span class="cb3">StructuralObject</span>


            <span class="cb1">return</span> Include(parent, (<span class="cb3">LambdaExpression</span>) expression);


        <span class="cb4">//Used for child collections of entities.</span>

        <span class="cb4">//Example: Order.OrderLines</span>

        <span class="cb1">public</span> <span class="cb1">static</span> <span class="cb3">ObjectQuery</span><span class="cb2"><</span>T<span class="cb2">></span> Include<span class="cb2"><</span>T<span class="cb2">></span>(<span class="cb1">this</span> <span class="cb3">ObjectQuery</span><span class="cb2"><</span>T<span class="cb2">></span> parent,

                                                <span class="cb3">Expression</span><span class="cb2"><</span><span class="cb5">Func</span><span class="cb2"><</span>T, <span class="cb3">RelatedEnd</span><span class="cb2">>></span> expression)

            <span class="cb1">where</span> T : <span class="cb3">StructuralObject</span>


            <span class="cb1">return</span> Include(parent, (<span class="cb3">LambdaExpression</span>) expression);


        <span class="cb1">private</span> <span class="cb1">static</span> <span class="cb3">ObjectQuery</span><span class="cb2"><</span>T<span class="cb2">></span> Include<span class="cb2"><</span>T<span class="cb2">></span>(<span class="cb3">ObjectQuery</span><span class="cb2"><</span>T<span class="cb2">></span> parent,

                                                 <span class="cb3">LambdaExpression</span> expression)

            <span class="cb1">where</span> T : <span class="cb3">StructuralObject</span>


            <span class="cb4">//There must be only one root entity to load related entities to it.</span>

            <span class="cb1">if</span> (expression<span class="cb2">.</span>Parameters<span class="cb2">.</span>Count <span class="cb2">!=</span> <span class="cb6">1</span>)


                <span class="cb1">throw</span> <span class="cb1">new</span> <span class="cb3">NotSupportedException</span>();


            <span class="cb4">//We'll store entity names here in order then join them at the end.</span>

            <span class="cb1">var</span> entityNames <span class="cb2">=</span> <span class="cb1">new</span> <span class="cb3">List</span><span class="cb2"><</span><span class="cb1">string</span><span class="cb2">></span>();

            <span class="cb4">//We split the calls ... Entity.MemberOfTypeChild.ChildMemberOfChildMember etc..</span>

            <span class="cb4">//Example: (Order ord) => ord.Customer.Address</span>

            <span class="cb1">string</span>[] childTypesMembers <span class="cb2">=</span> expression<span class="cb2">.</span>Body<span class="cb2">.</span>ToString()<span class="cb2">.</span>Split(<span class="cb7">'.'</span>);

            <span class="cb4">//Get the root entity type to start searching for the types of the members inside it.</span>

            <span class="cb4">//In prev. example: Find: Order</span>

            <span class="cb3">Type</span> parentType <span class="cb2">=</span> expression<span class="cb2">.</span>Parameters[<span class="cb6">0</span>]<span class="cb2">.</span>Type;

            <span class="cb4">//entityNames.Add(GetEntityNameFromType(parentType));</span>

            <span class="cb4">//The first word in the expression is just a variable name of the root entity. </span>

            <span class="cb4">//  Skip it and start next.</span>

            <span class="cb4">//In example: First part is: ord</span>

            <span class="cb1">for</span> (<span class="cb1">int</span> i <span class="cb2">=</span> <span class="cb6">1</span>; i <span class="cb2"><</span> childTypesMembers<span class="cb2">.</span>Length; i<span class="cb2">++</span>)


                <span class="cb1">string</span> memberName <span class="cb2">=</span> childTypesMembers[i];

                <span class="cb4">//Get the member from the root entity to get its entity type.</span>

                <span class="cb3">MemberInfo</span> member <span class="cb2">=</span> parentType<span class="cb2">.</span>GetMember(memberName)[<span class="cb6">0</span>];

                <span class="cb4">//We cannot get the type of the entity except by knowing</span>

                <span class="cb4">//  whether it's property or field (most likely will be property).</span>

                <span class="cb4">//Bad catch in the reflection API? Maybe!</span>

                <span class="cb3">Type</span> memberType <span class="cb2">=</span> member<span class="cb2">.</span>MemberType <span class="cb2">==</span> <span class="cb8">MemberTypes</span><span class="cb2">.</span>Property

                                      <span class="cb2">?</span> ((<span class="cb3">PropertyInfo</span>) member)<span class="cb2">.</span>PropertyType

                                      : ((<span class="cb3">FieldInfo</span>) member)<span class="cb2">.</span>FieldType;

                <span class="cb4">//Add the eneity name got from entity type to the list.</span>

                entityNames<span class="cb2">.</span>Add(GetEntityNameFromType(memberType));

                <span class="cb4">//The next member is belong to the child entity, so,</span>

                <span class="cb4">//  the root entity to seach for members should be the child entity type.</span>

                parentType <span class="cb2">=</span> memberType;


            <span class="cb4">//Join the entity names by "." again.</span>

            <span class="cb1">string</span> includes <span class="cb2">=</span> <span class="cb1">string</span><span class="cb2">.</span>Join(<span class="cb7">"."</span>, entityNames<span class="cb2">.</span>ToArray());

            <span class="cb4">//Simulate the original Include(string) call.</span>

            <span class="cb1">return</span> parent<span class="cb2">.</span>Include(includes);


        <span class="cb1">private</span> <span class="cb1">static</span> <span class="cb1">string</span> GetEntityNameFromType(<span class="cb3">Type</span> type)


            <span class="cb4">// We didn't just use the Entity type names because maybe</span>

            <span class="cb4">//  the table is called Orders and the class is Order or OrderEntity.</span>

            <span class="cb1">if</span> (type<span class="cb2">.</span>HasElementType) <span class="cb4">//For arrays, like: OrderLines[]</span>


                <span class="cb4">//The type of the element of the array is what we want.</span>

                type <span class="cb2">=</span> type<span class="cb2">.</span>GetElementType();


            <span class="cb1">else</span> <span class="cb1">if</span> (type<span class="cb2">.</span>IsGenericType) <span class="cb4">// for collections, like: EntityCollection<OrderLines></span>


                <span class="cb1">var</span> genericClassTypeParameters <span class="cb2">=</span> type<span class="cb2">.</span>GetGenericArguments();

                <span class="cb4">//The generic class must have one entity type only to load it.</span>

                <span class="cb1">if</span> (genericClassTypeParameters<span class="cb2">.</span>Length <span class="cb2">!=</span> <span class="cb6">1</span>)

                    <span class="cb1">throw</span> <span class="cb1">new</span> <span class="cb3">NotSupportedException</span>();

                <span class="cb4">//The type of the element of the collection is what we want.</span>

                type <span class="cb2">=</span> genericClassTypeParameters[<span class="cb6">0</span>];


            <span class="cb4">//Get the attributes that have the entity name in them.</span>

            <span class="cb1">var</span> entityTypeAttributes <span class="cb2">=</span>

                type<span class="cb2">.</span>GetCustomAttributes(<span class="cb1">typeof</span> (<span class="cb3">EdmEntityTypeAttribute</span>), <span class="cb1">true</span>) <span class="cb1">as</span> <span class="cb3">EdmEntityTypeAttribute</span>[];

            <span class="cb4">//Make sure there IS one and ONLY one attribute to get the only entity name.</span>

            <span class="cb1">if</span> (entityTypeAttributes <span class="cb2">==</span> <span class="cb1">null</span> <span class="cb2">||</span> entityTypeAttributes<span class="cb2">.</span>Length <span class="cb2">!=</span> <span class="cb6">1</span>)

                <span class="cb1">throw</span> <span class="cb1">new</span> <span class="cb3">NotSupportedException</span>();

            <span class="cb4">//Return the entity name.</span>

            <span class="cb1">return</span> entityTypeAttributes[<span class="cb6">0</span>]<span class="cb2">.</span>Name;




This enables you to write:

DbDataContext.Categories.Include( (cat)=> cat.Prodycts);


DbDataContext.Prodycts.Include( (prod)=> prod.Category);

According to your need.

For things like: Order.Customer.Address (multiple levels), you’ll have to write code like:

DbDataContext.Orders.Include( order => order.Customer ).Include( customer => Customer.Address );

What’s Eager Loading? (in case you don’t know)

Let’s say you have tables Products, and Categories with relation 1<->* between them (Any category has many products; one product has one category). Let’s say you want to display a page of all products grouped by categories. Something like the following list but with much more information of course:

    • Category 1
      • Product A
      • Product B
      • Product C
    • Category 2
      • Product X
      • Product Y
      • Product Z

If you are using some ORM / Code generator that creates for you classes like “Product”, “Category” and gives you properties like “myCategory.Products” , “myProduct.Category”, how would you create such page?

Normally you’ll put a repeater or such for products inside a repeater for categories.


The products repeater will have its data source set to the current category item of the Categories repeater, something like “( (CategoryEntity)Container.DataItem ).Products”. Fine with that? Familiar?

OK. Now, if the code generator that generated the “Products” property has something like that:

public List<PRoduct> _Products;

public List<PRoduct> Products




if (_Products == null)


_Products = (from products in DB.Products

where products.CategoryID == this.ID

select products)



return _Products;



  • Nevermind the LINQ syntax. It’s just like writing “SELECT * FROM [Products] WHERE …” with all the dataset/datareader stuff.

Lazy Loading (AKA. Deferred Loading)

If the generated code (or your code) looks like this, this means that that for every category in the database, you’ll have a separate DB call to get the products of this category.

It also means that the products of each category will not be loaded until someone writes code that calls the getter of the Products property. That’s why this style of coding (not loading the related objects until they’re asked to be loaded) is called Lazy Loading.

This is good for a single category where you may be seeking just the basic information of the category and will not try to load products, since then they will not be requested when you don’t ask for it.

However, this is very bad for our example page. Because it means that a new DB call for each category. Imagine that you have 20 or 50 or 100 Category there, this will give you how many DB calls? (Hint: N Categories + 1 call for the category list itself).

Eager Loading

What if the code in the getter above was in the constructor?. Imaging something like:

public Category(int categoryID)


// Code that laods category info from DB. Does not matter here.

//Could be in factory method or such. Not our topic

_CategoryID = categoryID;

// …. …. …. Continue Loading Logic

//The important part

_Products = (from products in DB.Products

where products.CategoryID == this.ID

select products)



This is good in case you know that in every situation when you use the category, the Products will be needed. This is probably not useful in a Product/category Scenario but think of a Person table and Address table where most likely whenever you load a Person you’re going to load his Addresses.

This is also useful especially when using ORM/code generator as in the first example. Lets get back to the Repeater example. If you use Entity framework or similar ORM, and you set the Categories query to load the Products eager loading (meaning each Category is created with its Products loaded already), Entity Framework can have a single connection and only TWO database hits, one for the Categories, and one for the Products. This is very useful in many listing scenarios. It also help especially when you have many parent objects (say Categories) or if the parent object needs to load entities of many different classes (say User needs to load Roles and Permissions and Personal Information and History and …. (if such case is applicable for you of course.

Now that you know what eager loading is, you can go up and check how the Entity Framework does that.