Home » excel » c# – Entity framework, dll, excel

c# – Entity framework, dll, excel

Posted by: admin April 23, 2020 Leave a comment


I have written dll in c# which is used by Excel (the dll is COM registered). I have no problem connecting with Excel. The dll retrieves data from a SQL Server database using Entity Framework 5. If I run the dll through a console app, the dll works fine. But when I run it through Excel (through VBA) I get a an InvalidOperationException. The error message is “No connection string named “MegaDailyEntities’ could be found in the application config file. This occurs the first time I try to retrieve data from the database.

I ran into this problem with the console app, but then I include the following in my App.config file

<?xml version="1.0" encoding="utf-8" ?>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
                <parameter value="v11.0" />
        <add name="MegaDailyEntities" connectionString="metadata=res://*/MegaDaily.csdl|res://*/MegaDaily.ssdl|res://*/MegaDaily.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=CQI-Laptop1;initial catalog=MegaDaily;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

and it worked fine.

So my question is, how do I get Excel to use this connection? Is there a config file for Excel?


How to&Answers:

The reason why connection string is not found is because .config files exist only for applications (.exe) but not for additional libraries (.dll)

Excel process tries to load connection string from Excel.exe.config, instead of loading from yourlibrary.dll.config

Working solution for this is to edit your *.context.tt file (EntityFramework classes generator) and update contructor for you DbContext.
You will find something like:

public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")

It should be possible to change it into

public <#=code.Escape(container)#>()
        : base("your EF connection string")

Or take a look how to set connection string from code