413

I have developed an application using Entity Framework, SQL Server 2000, Visual Studio 2008 and Enterprise Library.

It works absolutely fine locally, but when I deploy the project to our test environment, I am getting the following error:

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information

Stack trace: at System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark)

at System.Reflection.Assembly.GetTypes()

at System.Data.Metadata.Edm.ObjectItemCollection.AssemblyCacheEntry.LoadTypesFromAssembly(LoadingContext context)

at System.Data.Metadata.Edm.ObjectItemCollection.AssemblyCacheEntry.InternalLoadAssemblyFromCache(LoadingContext context)

at System.Data.Metadata.Edm.ObjectItemCollection.AssemblyCacheEntry.LoadAssemblyFromCache(Assembly assembly, Boolean loadReferencedAssemblies, Dictionary2 knownAssemblies, Dictionary2& typesInLoading, List`1& errors)

at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies)

at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyForType(Type type)

at System.Data.Metadata.Edm.MetadataWorkspace.LoadAssemblyForType(Type type, Assembly callingAssembly)

at System.Data.Objects.ObjectContext.CreateQuery[T](String queryString, ObjectParameter[] parameters)

Entity Framework seems to have issue, any clue how to fix it?

1
  • I solved it by deleting all the files from Azure and redeploying the API. Sep 7, 2020 at 13:40

38 Answers 38

620

This error has no true magic bullet answer. The key is to have all the information to understand the problem. Most likely a dynamically loaded assembly is missing a referenced assembly. That assembly needs to be in the bin directory of your application.

Use this code to determine what is missing.

using System.IO;
using System.Reflection;
using System.Text;

try
{
    //The code that causes the error goes here.
}
catch (ReflectionTypeLoadException ex)
{
    StringBuilder sb = new StringBuilder();
    foreach (Exception exSub in ex.LoaderExceptions)
    {
        sb.AppendLine(exSub.Message);
        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
        if (exFileNotFound != null)
        {                
            if(!string.IsNullOrEmpty(exFileNotFound.FusionLog))
            {
                sb.AppendLine("Fusion Log:");
                sb.AppendLine(exFileNotFound.FusionLog);
            }
        }
        sb.AppendLine();
    }
    string errorMessage = sb.ToString();
    //Display or log the error based on your application.
}
6
  • Thanks it helped me. But for some reason (have multi layer exceptions in my case) the line in the above code "catch (ReflectionTypeLoadException ex)" did not worked for me but I could see this exception type in my InnerExceptions (ReflectionTypeLoadException) and I could figure out the mismatch DLL info from LoaderExceptions.
    – Sai
    Sep 2, 2014 at 16:47
  • Good note here -- stackoverflow.com/a/38011925/503688 -- on how to diagnose this problem in a unit test project, but making the test project an executable and running it directly in the debugger (rather than going through the test harness).
    – yoyo
    Oct 19, 2016 at 21:24
  • 4
    just to find out fast what is missing, use throw new Exception(errorMessage);, hope helps someone.
    – Shaiju T
    Jan 24, 2017 at 13:18
  • Where do I put this code if it's a Windows Service?
    – Caloyski
    Jun 13, 2018 at 13:20
  • 4
    Without any extra code, in visual studio go to Exception Settings and put in the search box TypeLoadException then enable the couple hits checkboxes. Also you might have to disable in the options under the debug section "Just my code" so you can catch the exception when happening in a dependency you didn't write.
    – David Burg
    Dec 13, 2018 at 2:10
114

I solved this issue by setting the Copy Local attribute of my project's references to true.

4
  • 41
    When we keep drilling down the inner exceptions till we see the exception of type ReflectionTypeLoadException and It has a property "LoaderExceptions" which give the information about missing or mismatch DLL info. Then we can take care of the appropriate actions from there.
    – Sai
    Sep 2, 2014 at 16:50
  • 25
    well, that's fine when you are debugging from Visual Studio. But how about if you're web application only throw this error on the production server? even after you set the Copy Local attribute to true.
    – Yousi
    Oct 16, 2014 at 4:47
  • 5
    This is a solution for the problem on a production server, not on a local Visual Studio. Copy Local copies the referenced DLL at build-time and the DLL is first searched in the same folder as the running application. The problem could persist if you didn't copy the DLL that got copied at build-time to the correct folder on the production server. Oct 16, 2014 at 12:51
  • In my case I had to also add a nuget reference to Microsoft.AspNetCore.Mvc.ViewFeatures
    – MFedatto
    Aug 7, 2019 at 20:55
77

One solution that worked for me was to delete the bin/ and obj/ folders and rebuild the solution.

Update:

Or you can try to right-click the Solution node in the "Solution Explorer" and click "Clean Solution", then click "Rebuild Solution" (thanks Emre Guldogan)

4
  • I had to re-build the test project itself, not sure if you're referring to the test project here or the project you're testing. Jan 17, 2013 at 1:23
  • 6
    Another Re-comment: Right click the Solution node in the "Solution Explorer" and click "Clean Solution", then click "Rebuild Solution". (If there is a new addition in your source project - other projects in your solution - part(s), this causes the changes are to be reflected your project dll folder and solves this issue) Jun 23, 2016 at 11:51
  • I was having this issue. As suggested, I closed Visual Studio, Deleted bin folder, reopened the project and rebuild and it was successful.
    – Sagar S.
    Aug 1, 2016 at 11:15
  • This was happening when I was switching between branches with significant changes. Deleting the bin worked. Cleaning and Rebuilding were NOT working.
    – JGTaylor
    Jul 10, 2017 at 20:40
38

Two possible solutions:

  1. You are compiling in Release mode but deploying an older compiled version from your Debug directory (or vise versa).
  2. You don't have the correct version of the .NET Framework installed in your test environment.
5
  • It can also happen if your referenced DLL is "blocked". Right click on it, and select "unblock"
    – Ben
    Jun 10, 2010 at 10:05
  • 5
    Also found this to happen if one of the DLL projects was set to build "x64" instead of "Any CPU". May 16, 2012 at 18:07
  • #1 can occur if the solution configuration is incorrect - project not selected for build, for example after removing and adding again the project to solution
    – surfen
    Oct 10, 2012 at 0:19
  • How are those two solutions? Apr 26, 2017 at 9:15
  • i do release, and take my data from, release, actually i wholly delete my debug folder, and do not generate that. i have 4.6.1 on the server, but the project is 4.5.2 and it's dependency is 4.5.0, and i also use any CPU for both projects :| i also compare with another project, which run on same server, and the assembly they create and do refrence to / from are same. i mean the differences between being used from GAC, or Local Copy... Aug 20, 2017 at 9:54
19

The solution was to check the LoaderException: In my case, some of the DLL files were missing.

Enter image description here

18

As it has been mentioned before, it's usually the case of an assembly not being there.

To know exactly what assembly you're missing, attach your debugger, set a breakpoint and when you see the exception object, drill down to the 'LoaderExceptions' property. The missing assembly should be there.

Hope it helps!

3
  • 1
    Also we can keep drilling down the inner exceptions till we see the exception of type ReflectionTypeLoadException and It has a property "LoaderExceptions" which gives the information about missing or mismatch DLL info.
    – Sai
    Sep 2, 2014 at 16:52
  • 2
    In a solution with multiple projects, how do we see which project is causing the problem in LoaderExceptions? I see that System.Web.Mvc can't be found, but I don't know which of the 20 projects in this solution could be having the trouble.
    – mrcoulson
    Aug 1, 2018 at 17:28
  • I am still getting error. It is trying to load an assembly which has been updated in the new version. But it is still trying to load the older namespace which does not exist anymore. It is showing the correct and updated version of the assembly. "Could not load type 'Models.DatabaseProperty' from assembly 'Models, Version=1.0.22.0, Culture=neutral, PublicKeyToken=null'.'" DatabaseProperty Model does not exist in Models.DatabaseProperty. It has been updated to Models.Vault.DatabaseProperty in Version1.0.22.0. I have tried deleting the bin obj. @mkorman
    – Walter
    Jan 10, 2023 at 15:43
7

Make sure you allow 32 bits applications on IIS if you did deploy to IIS. You can define this on the settings of your current Application Pool.

6

I encountered this error with an ASP.NET 4 + SQL Server 2008 R2 + Entity Framework 4 application.

It would work fine on my development machine (Windows Vista 64-bit). Then when deployed to the server (Windows Server 2008 R2 SP1), it would work until the session timed out. So we'd deploy the application and everything looked fine and then leave it for more than the 20 minute session timeout and then this error would be thrown.

To solve it, I used this code on Ken Cox's blog to retrieve the LoaderExceptions property.

For my situation the missing DLL was Microsoft.ReportViewer.ProcessingObjectModel (version 10). This DLL needs to be installed in the GAC of the machine the application runs on. You can find it in the Microsoft Report Viewer 2010 Redistributable Package available on the Microsoft download site.

5

My instance of this problem ended up being a missing reference. An assembly was referred to in the app.config but didn't have a reference in the project.

5

Initially I tried the Fusion log viewer, but that didn't help so I ended up using WinDbg with the SOS extension.

!dumpheap -stat -type Exception /D

Then I examined the FileNotFoundExceptions. The message in the exception contained the name of the DLL that wasn't loading.

N.B., the /D give you hyperlinked results, so click on the link in the summary for FileNotFoundException. That will bring up a list of the exceptions. Then click on the link for one of the exceptions. That will !dumpobject that exceptions. Then you should just be able to click on the link for Message in the exception object, and you'll see the text.

5

If you're using the EntityDataSource in your project, the solution is in Fix: 'Unable to load one or more of the requested types' Errors. You should set the ContextTypeName="ProjectNameNameSpace.EntityContainerName" '

This solved my problems...

4

Another solution to know why exactly nothing works (from Microsoft connect):

  1. Add this code to the project:

    foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
    {
        asm.GetTypes();
    }
    
  2. Turn off generation serialization assemblies.

  3. Build and execute.
3

If you are using Entity Framework, try copying the following references locally.

  • System.Data.Entity
  • System.Web.Entity

Change the property "Copy Local" to "True" for these references and publish.

2

I had a .NET 4.0, ASP.NET MVC 2.0, Entity Framework 4.0 web application developed in Visual Studio 2010. I had the same problem, that it worked on one Windows Server 2008 R2 server but not on another Windows Server 2008 R2 server, even though the versions of .NET and ASP.NET MVC were the same, throwing this same error as yours.

I went to follow miko's suggestion, so I installed Windows SDK v7.1 (x64) on the failing server, so I could run !dumpheap.

Well, it turns out that installing Windows SDK v7.1 (x64) resolved the issue. Whatever dependency was missing must have been included in the SDK. It can be downloaded from Microsoft Windows SDK for Windows 7 and .NET Framework 4.

2

Adding my specific problem/solution to this as this is the first result for this error message. In my case, the error was received when I deployed a second application within the folder of my first application in IIS. Both were defining connection string with the same name resulting in the child application having a conflict and in turn generating this (to me) non-obvious error message. It was solved by adding:

<clear/>

in the connection string block of the child web application which prevented it from inheriting the connection strings of web.config files higher in the hierarchy, so it looks like:

<connectionStrings>
  <clear/>
  <add name="DbContext" connectionString="MySERVER" providerName="System.Data.SqlClient" />
</connectionStrings>

A reference Stack Overflow question which helped once I determined what was going on was Will a child application inherit from its parent web.config?.

2

This worked for me. Add it in your web.config

<system.web>
  <trust level="Full" />
1
  • I got this error : It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
    – user4227915
    Nov 10, 2015 at 14:08
2

My issue has been resolved after I deleted the redundant assembly files from the bin folder.

2

In case none of the other answers help you:

When I had this problem, it turned out my Windows service was built for an x64 platform, and I was inadvertently running the 32-bit version of InstallUtil.exe. So make sure you're using the right version of InstallUtil for the platform you built for.

1
  • I had a similar issue. Some of the DLLs my service was using were compiled for 32-bit processor, changed to any processor and it works now. Nov 11, 2016 at 14:03
1

Other suggestions are all good. In my case, the problem was that the developer box was a 64-bit machine using the x86 location of various APIs, including Silverlight.

By changing the target platform to match the 32-bit server where the web application was being deployed removed the majority of the errors related to not being able to load one or more of the requested types.

1

I changed the Specific Version Property of the Refrences to false and that helped.

1

I had the same error message reported when compiling a Visual Studio package (VSPackage). The whole solution compiles and the error is thrown when the package is being created by CreatePkgDef. Having said that, it is clear that I cannot catch the LoaderExceptions as it is not my application that throws it, but Microsoft's own tool. (Though I am responsible for the confusion of CreatePkgDef.)

In my case the root cause was that my solution creates a MyDll.dll that has already been registered to the GAC (and they are different), so the CreatePgkDef got confused which one to use and it decided just to throw an error which isn't really helpful. The MyDll.dll in the GAC was registered by the installer of the same product (obviously an earlier version, with /slightly/ different content).

How to fix it

  1. Preferred way: Make sure you use the correct version of MyDll.dll
    1. When compiling your project make sure you use a different version number than you used in the previous version located in the GAC. Make sure the following attributes are correct:
      • [assembly: AssemblyVersion("1.0.0.1")] // Assuming the old DLL file was versioned 1.0.0.0
      • [assembly: AssemblyFileVersion("1.0.0.1")] // Assuming the old DLL file was versioned 1.0.0.0
    2. If needed, specify the fully qualified assembly name (for example, "MyDll.dll, Version=1.0.0.1, Culture=neutral, PublicKeyToken=1234567890abcdef") when you reference it in your other projects.
  2. If the above failed: You can uninstall the old MyDll.dll from GAC
    1. How to Uninstall an Assembly from the GAC
    2. Uninstall the application that includes MyDll.dll

Changing the AssemblyVersion was good enough for me. :)

I hope this was helpful.

1

I had the same issue (but on my local) when I was trying to add Entity Framework migration with Package Manager Console.

The way I solved it was by creating a console application where Main() had the following code:

 var dbConfig = new Configuration();
 var dbMigrator = new DbMigrator(dbConfig);
 dbMigrator.Update();

Make sure the Configuration class is the migration Configuration of your failing project. You will need System.Data.Entity.Migrations to use DbMigrator.

Set a breakpoint in your application, and run it. The exception should be caught by Visual Studio (unless you have that exception type set to not break the debug session), and you should be able to find the info you are looking for.

The missing reference in my case was EFProviderWrapperToolkit.

1

I got this problem when I installed a NuGet package on one of the projects and forgot to update the other project.

I solved this by just making both projects having the same reference assembly.

0
1

It happened for me also. I solved the problem as follows: Right click Solution, Manage NuGet Packages for Solution... Consolidate packages and upgraded the packages to be in the same version.

1

I had this issue while referencing a nuget package and later on using the remove option to delete it from my project. I had to clear the bin folder after battling with the issue for hours. To avoid this its advisable to use nuget to uninstall unwanted packages rather than the usual delete

0

Set 32 bit IIS mode to true, debug mode to true in the configuration file, deleting the temp directory and resetting IIS fixes the issue temporally and it comes back after some time.

0

Verify that each of your projects is setup correctly in the Configuration Manager.

Similar to William Edmondson's reason for this issue, I switched my Configuration Manager setting from "Debug" "Any CPU" to "Debug" ".NET". The problem was that the ".NET" version was NOT configured to build ALL of the projects, so some of my DLLs were out of date (while others were current). This caused numerous problems with starting the application.

The temporary fix was to do Kenny Eliasson's suggestion to clean out the \bin and \obj directories. However, as soon as I made more changes to the non-compiling projects, everything would fail again.

0

I also got this issue when create new Microsoft Word add-in with Visual Studio 2015. The issue is about I have 2 versions of MS Office, 2013 and 2016. I uninstall MS Office 2013 and then it works.

0

I build a few projects for SharePoint and, of course, deployed them. One time it happened.

I found an old assembly in C:\Windows\assembly\temp\xxx (with FarManager), removed it after reboot, and all projects built.

I have question for MSBuild, because in project assemblies linked like projects and every assembly is marked "Copy local", but not from the GAC.

0
0

I am able to fix this issue by marking "Copy Local=True" on all referenced DLL files in the project, rebuilding and deploying on a testing server.

Not the answer you're looking for? Browse other questions tagged or ask your own question.