InternetException

About coding and whatnot.

Mapping collection of entities in EF with AutoMapper

clock May 25, 2013 11:38 by author n.podbielski

In my last post I explained why is useful to add base entity class in EF. Today I will write how with use of this base class an AutoMapped map collection of data objects (i.e. DTOs to existing collection of entities).

Problem with doing:

dataColection.MapTo(entitiyCollection);

is that AutoMapper removes all entities from entity collection because data item mapped to entity has diffrent hash code and diffrent reference then original entity. Then when AutoMapper search for same item in original entity collection as mapped entity, it can not find one. That is causing AutoMapper to ads another one entity with the same Id as original, after removing original entity. Entity collection changed in that way cannot be saved to database, because EF complaints that removed entities has to be removed explicitly from database on commit.

To fix that problem we will use custom ValueResolver. To create one we will create class which will derive from IValueResolver available in AutoMapper assembly.

public interface IValueResolver
{
    ResolutionResult Resolve(ResolutionResult source);
}

There is also available ValueResolver<T1,T2>:

public abstract class ValueResolver<TSource, TDestination> : IValueResolver
{
    protected ValueResolver();

    public ResolutionResult Resolve(ResolutionResult source);
    protected abstract TDestination ResolveCore(TSource source);
}

But this class make available to override only ResolveCore method, which will be not sufficient since it does not have information about destination type of entity. Without this infomation wi wont be able to create generic resolver class. So instead this class we will use intrerface.

Our generic mapping class has to take two type parameters type of data object (DTO) and type of entity. Also ResolutionResult object of auto mapper mapping context does not have information of which source member is being mapped inside ValueResolver. This information has to be passed to. It is best to passed it as expression instead of a string, to make it less error prone. To make it possible we will add third type parameter which will be parent type of data object collection.

public class EntityCollectionValueResolver<TSourceParent, TSource, TDest> : IValueResolver
    where TSource : DTOBase
    where TDest : BaseEntity, new()
{
    private Expression<Func<TSourceParent, ICollection>> sourceMember;

    public EntityCollectionValueResolver(Expression<Func<TSourceParent, ICollection>> sourceMember)
    {
        this.sourceMember = sourceMember;
    }

    public ResolutionResult Resolve(ResolutionResult source)
    {
        //get source collection
        var sourceCollection = ((TSourceParent)source.Value).GetPropertyValue(sourceMember);
        //if we are mapping to existing collection of entities...
        if (source.Context.DestinationValue != null)
        {
            var destinationCollection = (ICollection<TDest>)
                //get entities collection parent
                source.Context.DestinationValue
                //get entities collection by member name defined in mapping profile
                .GetPropertyValue(source.Context.MemberName);
            //delete entities that are not in source collection
            var sourceIds = sourceCollection.Select(i => i.Id).ToList();
            foreach (var item in destinationCollection.ToList())
            {
                if (!sourceIds.Contains(item.Id))
                {
                    destinationCollection.Remove(item);
                }
            }
            //map entities that are in source collection
            foreach (var sourceItem in sourceCollection)
            {
                //if item is in destination collection...
                var originalItem = destinationCollection.Where(o => o.Id == sourceItem.Id).SingleOrDefault();
                if (originalItem != null)
                {
                    //...map to existing item
                    sourceItem.MapTo(originalItem);
                }
                else
                {
                    //...or create new entity in collection
                    destinationCollection.Add(sourceItem.MapTo<TDest>());
                }
            }
            return source.New(destinationCollection, source.Context.DestinationType);
        }
        //we are mapping to new collection of entities...
        else
        {
            //...then just create new collection
            var value = new HashSet<TDest>();
            //...and map every item from source collection
            foreach (var item in sourceCollection)
            {
                //map item
                value.Add(item.MapTo<TDest>());
            }
            //create new result mapping context
            source = source.New(value, source.Context.DestinationType);
        }
        return source;
    }
}

 Expression of type Expression<Func<TSourceParent, ICollection>> help as to make sure that inside Resolve method we will get correct property without necessity of using existing object source or creating new one to pass in inside some lambda.
 GetPropertyValue method is extension of object type. It works by taking MamberExpression from our Expression<Func<TSourceParent, ICollection>>, and then property MamberExpression.Member.Name of source member. After that with source property name we can take its value with reflection:

public static TRet GetPropertyValue<TObj, TRet>(this TObj obj,
	Expression<Func<TObj, TRet>> expression,
	bool silent = false)
{
	var propertyPath = ExpressionOperator.GetPropertyPath(expression);
	var objType = obj.GetType();
	var propertyValue = objType.GetProperty(propertyPath).GetValue(obj, null);
	return propertyValue;
}

public static MemberExpression GetMemberExpression(Expression expression)
{
	if (expression is MemberExpression)
	{
                return (MemberExpression)expression;
}
else if (expression is LambdaExpression)
{
var lambdaExpression = expression as LambdaExpression;
if (lambdaExpression.Body is MemberExpression)
{
return (MemberExpression)lambdaExpression.Body;
}
else if (lambdaExpression.Body is UnaryExpression)
{
return ((MemberExpression)((UnaryExpression)lambdaExpression.Body).Operand);
}
}
return null;
}

Whole Resolve method is enclosed in if statement:

if (source.Context.DestinationValue != null)

this will ensure that we cover 2 case when we map data collection to existing collection of entities and to new collection of entities. Second case is inside else and is not complicated since it is simple mapping of all items inside collection.
 Interesting part is happening inside if and it is composed from three phases:

1. Deleting of entities

All entities from destination collection, that are not present inside our data collection, are being deleted. That prevents EF from throwing an error mentioned above. Entities and DTOs have both Ids, which are used to find which of items was deleted. This is where base entity class is useful since it has Id defined inside.

2. Mapping changed items.

If entity with the same Id as item in data collection has been found, it is being used as destination of mapping

3. Mapping of new (added) entities, as new objects.

 This generic class then can be used as this inside AutoMapper profile:

CreateMap<ParentDTO,ParentEntity>()           
                .ForMember(o => o.DestinationCollection, m =>
                        m.ResolveUsing(new EntityCollectionValueResolver<
                            ParentDTO, SourceDTO, DestEntity>
                            (s => s.SourceCollection))
                           )
            ;

One more thing: this solution will cause StackOverflowException if SourceDTO to DestEntity mapping profile will try to map again ParenDTO -> ParentEntity, from ParentEntity property inside DestEntity. Usually child entities has reference to parent entities. If they are not ignored during mapping, AutoMapper will try do mapping: ParentDTO -> SourceCollection -> SourceDTO -> SourceEntity -> ParentDTO which will cause circular mapping.

Also this resolver will not cover case when Destination Collection is collection of derived items from parent item. For example when you have collection of people with students and teachers inside it, this will try to do mapping only for people. All derived types data will be ignored.

Unfortunately this will be not enough to map collection. Its because even items are removed collection, they are not set for deletion inside DbContext class. This will cause critical error in application during SaveChanges method in DbContext. To correct that issue we have to mark them for deletion from context class.

To do that there are 3 options:

1. Use context class inside EntityCollectionValueResolver class and mark deleted items for deletion. This is less elegant, but much more quick solution.

2. Use custom collection class which will mark deleted items for deletion using context class

3. Use custom collection class with items state tracking. This collection could subscribe an OnSaveChanges event of DBContext class in which event handler delete from context items deleted before from collection.

First and second options (maybe third too, it depends from implementation) will suffer from necessity to synchronize DbContext which will be used to save changes inside parent entity. Entity which was mapped from DTO. Also first solution is less elegant because is mixing AutoMapper and DbContext. Those two should live separately.

In this article I will show second option since third, which is better I think will involve changing of entities classes and repositories. It's to much for one article.

First, we have to acquire instance of context class. In my application I have IoC container which have single-for-thread instance of this class. This makes sure of synchronization of Context which loaded parent entity, deletes child entities and will save changes to parent entity.

At the beginning of the method Resolve we will add code that will return current instance of Context class (example with using Microsoft Patterns & Practices IServiceLocator implementation):

var context = ServiceLocator.GetInstance<DbContext>();

With this instance we can delete items from context:

if (!sourceIds.Contains(item.Id))
{
    destinationCollection.Remove(item);
    ((IObjectContextAdapter)context).ObjectContext.DeleteObject(item);
}

After that ObjectContextManager private property _entriesWithConceptualNulls, will have 0 items, which is good because any item in this collection will cause EF to throw critical error.

With breakpoint set after line with DeleteObject method call, you can see this collection with expression:

(context.Database._internalContext).ObjectContext.ObjectStateManager._entriesWithConceptualNulls

as like in the image:

 

This is whole body of Resolve method:

public ResolutionResult Resolve(ResolutionResult source)
{
        var context = ServiceLocator.GetInstance<DbContext>();
        //get source collection
        var sourceCollection = ((TSourceParent)source.Value).GetPropertyValue(sourceMember);
        //if we are mapping to existing collection of entities...
        if (source.Context.DestinationValue != null)
        {
            var destinationCollection = (ICollection)
                //get entities collection parent
                source.Context.DestinationValue
                //get entities collection by member name defined in mapping profile
                .GetPropertyValue(source.Context.MemberName);
            //delete entities that are not in source collection
            var sourceIds = sourceCollection.Select(i => i.Id).ToList();
            foreach (var item in destinationCollection.ToList())
            {
                if (!sourceIds.Contains(item.Id))
                {
                    destinationCollection.Remove(item);
                    ((IObjectContextAdapter)context).ObjectContext.DeleteObject(item);
                }
            }
            //map entities that are in source collection
            foreach (var sourceItem in sourceCollection)
            {
                //if item is in destination collection...
                var originalItem = destinationCollection.Where(o => o.Id == sourceItem.Id).SingleOrDefault();
                if (originalItem != null)
                {
                    //...map to existing item
                    sourceItem.MapTo(originalItem);
                }
                else
                {
                    //...or create new entity in collection
                    destinationCollection.Add(sourceItem.MapTo());
                }
            }
            return source.New(destinationCollection, source.Context.DestinationType);
        }
        //we are mapping to new collection of entities...
        else
        {
            //...then just create new collection
            var value = new HashSet();
            //...and map every item from source collection
            foreach (var item in sourceCollection)
            {
                //map item
                value.Add(item.MapTo());
            }
            //create new result mapping context
            source = source.New(value, source.Context.DestinationType);
        }
        return source;
    }
}

From now on after mapping from DTO to entity with automapper and saving mapped entity to database should work just fine.

That is all! Smile



Entity Framework and Base Entity class

clock May 16, 2013 14:32 by author n.podbielski

Entity Framework does great job with taking care of entities changes and entities collection internally. And its uses almost plain POCO objects. Almost because collections of dependents data like in 1 to many tables relationship needs virtual keyword. Its understandable since EF needs to track what happens to collection. For instance lets have 2 tables: Customer and dependent Order.

To map this relation in EF model we need to create two classes: Customer with relationship to Orders collection and Order with relationship to single Customer. Both end of relation needs to be virtual. Oh well. Actually they aren't have to be virtual, but as you can read here this allow for 'lazy loading' and 'change tracking' capabilities of EF, so its pretty useful to add virtual keywords in those places.

public partial class Customer
{
public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Order> Orders { get; set; } } public partial class Order {
public int Id { get; set; } public virtual Customer Customer { get; set; } }

That's pretty much it. There some rare cases when for example useful is to initialize collection of child entities on entity creation but its not requirement from EF point of view. So what could be the reason to add base class for entity?

Thing is that whenever you want to transfer entity to some another subsystem to make changes there, Entity Framework cannot and could not track those changes (you NEVER EVER should transfer entity object directly but map it to some other data object first!). Mapping data from entity to some data transfer object (DTO), making changes and returning them again to EF, will more likely fail. With simple object its achievable and should working, but it can spawn errors with collections mapping. In last application I was working that was the case. But I used EntityFramework.Patters extension so, in pure EF this can work fine (but I doubt it).

Root of the problem was Order collection in Customer entity. When I tried to transfer customer through i.e. WCF service, make changes at client side, and return them to EF, it caused EF to think that I deleted all items from Orders, and added some new instead. Its cool that it can tell that collection changed. To bad that this happens even when it not changed at all! To be frank EF wasn't entirely responsible it was mapping mechanism in AutoMapper. It wasn't considering two Order items with same values the same because they weren't referencing same object. After replacing old Order with new Order in AutoMapper, EF wasn't considering them equal for exactly same reason: reference to them was different.

How to remedy that? There have to be some custom mechanism of entities equality. And its best to that on some BaseEntity object, right?

public class BaseEntity : BaseEntity where TEntity : BaseEntity
    {
        private int? oldHashCode;

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            if (obj == this)
            {
                return true;
            }
            if (obj is TEntity)
            {
                var objAsBaseEntity = obj as TEntity;
                return objAsBaseEntity.Id == this.Id;
            }
            return false;
        }
    }

This implementation is partly based on MSDN Equals guidelines and on base entity class I have found for NHibernate. But is not enough.  With Equals implementation we have to implement also GetHashCode. Problem with this is that, new entity should have whole time its exists the same hash code. More important hash code should be only dependent on Id property, which is only thing that allow two separate objects to be equal. So we need to make entity hash code dependent on id. But what about two new objects? They will have empty id and because of that the same hash code? One solution is to make hash code to be generated from base class when Id is empty.

public override int GetHashCode()
{
    // once we have a hashcode we'll never change it
    if (oldHashCode.HasValue)
    return oldHashCode.Value;
    // when this instance is new we use the base hash code
    // and remember it, so an instance can NEVER change its
    // hash code.
    var thisIsNew = Id == Guid.Empty;
    if (thisIsNew)
    {
        oldHashCode = base.GetHashCode();
        return oldHashCode.Value;
    }
    return Id.GetHashCode();
}

When id is set, hash code is generated from it. When it is not set, hash code is generated from base class which is object in our case. And first time hash code is generated is final. Hash code cannot be changed. It is because it would brake functionality of HashSet and Dictionary classes. EF uses both of them so it would be big issue. It is best implementation I could find, and still it have some drawbacks. For example entity loaded from DB and mapped from outside of EF with the same data and the same Id will have different hash code. It is because in first situation hash code is generated from database id. In second situation hash code is generated from new object which have empty id. It does not matter that after hash code generation id is set to real value. Once it is generated it can not be changed.

To remedy that we need to make mapping of mapped entities and entities loaded from DB by hand.
In next post I will explain how to make class that will resolve mapping of entities to correct this issue.

 

 



Ninject and Entity Framework

clock May 3, 2013 03:50 by author n.podbielski

Last time I wrote about problem with testing Entity Framework in Visual Studio 2012. During working on this project I also encounter problems with configuration of Ninject to allow injecting Entity Framework classes from its Patterns extension. To be frankly this was not much a problem then lack of documentation. I just was forced to experiment with Ninject and new-thing-for-me Entity Framework Patterns extension.

So to make world of .NET a little easier I decided to write about my experience.

I started with this documentation for EF extension. It is instruction for someone that decided to use Unity in their project.

There is also link to similar instruction with Ninject IoC container, but its empty. Why authors of this extension decided to include in documentation of their project link to something that is empty eludes me. Oh well you have to make through with things you have. It should not be hard to translate Unity configuration syntax to its equivalent in Ninject.

 

public static class CompositionRoot
    {

        private static readonly IUnityContainer UnityContainer = new UnityContainer();

        public static IUnityContainer Container { get { return UnityContainer; } }

        public static void RegisterServices()
        {
            // Registering interfaces of Unit Of Work & Generic Repository
            UnityContainer.RegisterType(typeof(IRepository<>), typeof(Repository<>));
            UnityContainer.RegisterType(typeof(IUnitOfWork), typeof(UnitOfWork));

            // Every time we ask for a EF context, we'll pass our own Context.
            UnityContainer.RegisterType(typeof(DbContext), typeof(Context));

            // Tricky part.
            // Your repositories and unit of work must share the same DbContextAdapter, so we register an instance that will always be used
            // on subsequente resolve.
            // Note : you should not use ContainerControlledLifetimeManager when using ASP.NET or MVC
            // and use a per request lifetime manager
            UnityContainer.RegisterInstance(new DbContextAdapter(UnityContainer.Resolve()), new ContainerControlledLifetimeManager());

            UnityContainer.RegisterType(
                new InjectionFactory(con => con.Resolve())
                );

            UnityContainer.RegisterType(
                new InjectionFactory(con => con.Resolve())
                );
        }
    }

As you can see it is a little convoluted. That is one of reasons why I like Ninject more. It is cleaner.

Oh right. First lets create Ninject module:

public class InjectModule : NinjectModule
    {
        public override void Load()
        {
           
        }
    }

Modules like that one are used by Ninject in following way:

var kernel = new StandardKernel();
kernel.Load<InjectModule>();

Depending of where you are starting Ninject container it can look a little diffrent but idea is the same you are using modules for registering packs of types. Using that i created module for EF in EF assembly and that way it can be shared in my tests, services, console applications etc.

Now lets fill this new module with meaningfull code. Firstly we will register repository and unit of work interfaces:

Bind(typeof(IRepository<>)).To(typeof(Repository<>));
Bind<IUnitOfWork&gt().To<UnitOfWork&gt();

Isn't that cleaner than Unity syntax? Next we need to register EF context class. It is as simple as:

Bind<DbContext>().To<DBEntities>();

Ofcourse DBEntities is your type of EF context class.

Now the harder part, a Unity 'tricky' registering of DBContextAdapter class. What we trying to do here is to make every instance of Repository and UnitOfWork, that is created by Ninject and is transient, created whenever necessary and then disposed, had to share same instance of DBContextAdapter. I decided to make this class single for thread scope. It is not ideal but is bult-in behavior of Ninject. In best case it should be shared for our whole application inlcuding spawned threads. Or for Web apps it could be better to use InRequestScope

Bind<DbContextAdapter>().To<DbContextAdapter>().InThreadScope();

To bind interfaces used by UnitOfWork an Repository classes, which allow them use context class indirectly through shared DBContextAdapter class, we have to bind those interfaces to shared instance of this class. To do that we register interfaces IObjectSetFactory (used by repository) and IObjectContext (used by UnitOfWork) with custom method that returns DBContextAdapter:

Bind<IObjectSetFactory, IObjectContext>()
               .ToMethod(con =>con.Kernel.Get<DbContextAdapter>());

Whole module for configuration of EF will looks like this:

 

public class EFModule : NinjectModule
{
public override void Load()
{
Bind(typeof(IRepository<>)) .To(typeof(Repository<>));
Bind<IUnitOfWork>().To<UnitOfWork>();
Bind<UnitOfWork>().ToSelf();
Bind<DbContext>().To<DBEntities>();
Bind<DbContextAdapter>().To<DbContextAdapter>().InThreadScope();
Bind<IObjectSetFactory, IObjectContext>()
.ToMethod(con =>con.Kernel.Get<DbContextAdapter>());
}
}


This is sufficient to make EF with Patterns extension working in our application.

this.kernel = new StandardKernel();
kernel.Load();
repository = kernel.Get<IRepository>();

var uow = kernel.Get<IUnitOfWork>();
repository.Insert(new Enity{});
uow.Commit();

This is it. Operation with UoW and repository pattern should work with EF.

Personally I am unhappy that this particular implementation of UnitOfWork does not implement IDisposable interface. This would greatly improve clarity of code as would be helpfull during maintaining of the code.

this.kernel = new StandardKernel();
kernel.Load();
repository = kernel.Get<IRepository>();

using(var uow = kernel.Get<IUnitOfWork>())
{
	repository.Insert(new Enity{});
	uow.Commit();
}

But you cant have everything Smile



Entity Framework Patterns extension and Unit Test in Visual Studio 2012

clock April 23, 2013 02:18 by author n.podbielski

Yesterday I was trying to make work simple test class in VS2012. I did not know what was wrong exactly. It was first project when I tried to glue together Entity Framework with repository pattern and Ninject as IoC container. Because of the fact that this was first time for solution like that I was sure that it is me, or rather source of my problem was indeed my code. But let's not skip ahead.

So when I manage to translate adding EF classes to Unity from here: IoC : using EntityFramework.Patterns with Unity 2.1 into Ninject language. I got error like this from VS (when tried to running test case):


Result Message:    Unable to create instance of class UnitTest. Error: System.IO.FileLoadException: Could not load file or assembly 'EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040).
Result StackTrace:   
at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
   at System.Signature..ctor(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
   at System.Reflection.RuntimeConstructorInfo.GetParametersNoCopy()
   at System.Reflection.RuntimeConstructorInfo.GetParameters()
   at Ninject.Injection.DynamicMethodInjectorFactory.EmitLoadMethodArguments(ILGenerator il, MethodBase targetMethod) in c:\Projects\Ninject\ninject\src\Ninject\Injection\DynamicMethodInjectorFactory.cs:line 115
   at Ninject.Injection.DynamicMethodInjectorFactory.Create(ConstructorInfo constructor) in c:\Projects\Ninject\ninject\src\Ninject\Injection\DynamicMethodInjectorFactory.cs:line 40
   at Ninject.Planning.Strategies.ConstructorReflectionStrategy.Execute(IPlan plan) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Strategies\ConstructorReflectionStrategy.cs:line 67
   at Ninject.Planning.Planner.<>c__DisplayClass1.<CreateNewPlan>b__0(IPlanningStrategy s) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Planner.cs:line 109
   at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action) in c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:line 32
   at Ninject.Planning.Planner.CreateNewPlan(Type type) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Planner.cs:line 109
   at Ninject.Planning.Planner.GetPlan(Type type) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Planner.cs:line 71
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 77
   at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
   at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 197
   at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 165
   at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 114
   at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
   at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
   at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37
   at UnitTest..ctor()

So my first thought was: heck, I probably did something wrong and it not so easy (Ninject registrations of components is really easy, you should try yourself). But I cannot find any references to that version of EF anywhere in my project. In fact I did not added them myself, everything was done by NuGet, so it should work, right? Yes. It should and it was working because:

1. Registration of classes from EntityFramework.dll was working perfectly.

2. Registration of classes from EntityFramework.Pattersn.dll was not working at all.

3. When I added console project registration of both types from both assemblies was working without problems.

So the problem was with EntityFramework.Patterns.dll, its internal reference to older version of EF (I was using 5.0 version). Another problem was with assembly redirecting from older version of EF to newer 5.0. In console project section in app.config:

 <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
   </assemblyBinding>
  </runtime>

was doing what it suppose to, forcing application to use 5.0 version despite internal reference to version 4.3.1 inside EntityFramework.Patterns.dll. So maybe in test it is not present. Nope it was. Maybe configuration is not copied into Debug dir? Nope. Maybe it is named wrong? Nope. In this moment I had to take a few minutes off.

I was thinking: everything is as it suppose to. Assemblies, references, redirecting, configuration. So... maybe test environment is not starting correctly? Maybe it is ignoring that part of app.config. When I was adding NuGet packages same day I noticed update for VS. Why not tried that? Few clicks, about 1 hour and restart of VS after I tried again. Guess what? It worked!

So it was bug with VisualStudio. I was glad that it was over and little disappointed for few hours that I have lost. But it was at least one step closer in the right direction. Smile

 

So if you encounter problem like that tried update VS 2012 with Update 2. It should work!