28 Jan
2010

The Entity Framework and the “The invoked member is not supported in a dynamic assembly” exception.

Category:UncategorizedTag: :

When you create an entity model, a few mapping files are created for you; namely .cdsl, .ssdl, and .msl.  Right about now you may be saying to yourself, I don’t see those files anywhere. That is because they are actually stored as a resource in the assembly you created your entity model.  When you create your entity model, an entity connection string is also created for you and placed in an App.config file, and may resemble the following:

<connectionStrings>
   <add name="BATEntities" connectionString="metadata=res://*/BAT.DataModel.csdl|res://*/BAT.DataModel.ssdl|res://*/BAT.DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=CREATIV-DESKTOP\MSSQLSERVER2008;Initial Catalog=BoiseAutoTrader;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
 </connectionStrings>

The entity connection string tells the EF which assembly to look for the mapping files. By default it is represented by the asterisk (*). The bad thing about this is that the * instructs EF to look in all assemblies in your application domain until it finds them. So, you’re probably thinking that this can cause performance issues, and you are absolutely right about that. But the real problem is when your application uses dynamic assemblies and cannot give out their resources. In this case an exception will be thrown, “The invoked member is not supported in a dynamic assembly”.

So how do we fix this? Simple, just fully qualify your assembly name in your entity connection string by replacing the * with your assembly name as follows:

<connectionStrings>
   <add name="BATEntities" connectionString="metadata=res://MyAssembly/BAT.DataModel.csdl|res://MyAssembly/BAT.DataModel.ssdl|res://MyAssembly/BAT.DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=CREATIV-DESKTOP\MSSQLSERVER2008;Initial Catalog=BoiseAutoTrader;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>