Search code examples
c#entity-frameworkexceptionassembly-referencescsharpcodeprovider

CSharpProvider runtime compilation failing to find a DLL


I am compiling a DLL at runtime using CSharpCodeProvider. My code runs fine on some machines but on otherse it fails with the following error:

error CS0006: Metadata file 'EntityFramework.dll' could not be found

Here is a code snippet:

var csFile = ... // the file is in C:\Program Data\MyFolder\InnerFolder
using (var provider = new CSharpCodeProvider())
{
    var parameters = new CompilerParameters
    {
        GenerateInMemory = false, // we want the dll saved to disk
        GenerateExecutable = false,
        CompilerOptions = "/target:library",

        // the assembly is compiled to the same directory as the .cs file
        OutputAssembly = GetNewCacheAssemblyPath(),
    };

    parameters.ReferencedAssemblies.AddRange(new[]
        {
            "System.dll", 
            "System.Data.dll", 
            "System.Data.Entity.dll", 
            "EntityFramework.dll",
        });

    var compilerResult = provider.CompileAssemblyFromFile(parameters, csFile);
}

Any thoughts as to why this might be happening?


Solution

  • EntityFramework is not part of the .NET framework. So a simple explanation is that the machine this fails on doesn't have it installed. You are supposed to deploy it yourself. When you use the Nuget package then you'll have a copy of the DLL in your bin\Release directory. Don't forget to include it with your shipping binaries.

    Next failure mode is that you did deploy it but the working directory of the program is not where you hope it is. Provide the full path name of the assembly to avoid this. You can use, say, Assembly.GetEntryAssembly().Location to find the path of the EXE.