Monday, January 24, 2011

Entity Framework 4 and Partial Trust

Aaaggghhh. It’s been a little while since I’ve been plagued by trust issues on a hosting provider. And now I’ve hit one trying to move a site onto the Rackspace Cloud.

It seems that they force all code to run in partial trust and that stops Entity Framework 4 from running. It seems that it’s a known issue for EF3.5 but it seems that it also occurs in EF4.

You can see it in action running locally by adding the following to web.config:

<system.web>
<trust level="Medium" />
</system.web>
So after some considerable digging, going round in circles, and swearing at anything to do with EF4 I came upon this article on the Knowledge Base - ASP.NET Web sites That Have EDMX files do not compile and deploy in partial trust.

It seems that the website that I’ve created is not a full Web Application Project but is some half way house – there is a compiled assembly but because it’s MVC the views are left as aspx/ascx files. This means that the site is dynamically built and the metadata files extracted and then compiled into the required assembly. Which fails with a SecurityException – because System.Data.Entity.Design won’t run in partial trust and it’s used if you don’t have a fully pre-compiled Web Application Project.

So eventually I hacked a solution together…
  1. Stop the metadata files being compiled into the assembly as a resource by setting the “Metadata Artifact Processing” to “Copy to Output Directory”.
  2. Add a pre-build task to copy the three metadata files to the bin folder in the web site itself.
  3. If publishing directly from Visual Studio to the hosting provider then also set the three metadata files as Content files so that they’re transferred across.
  4. Reference the metadata files in the web.config version of the connection string correctly in the ~\bin folder.
So it’s not an easy solution and it’s not really tied to the 3.5 problem that I first thought it was.

What complicated the solution was that I do have the EF Model in it’s own project so the metadata shouldn’t need to be interrogated. And I thought I had a Web Application Project (which I apparently don’t even though I’ve got a compiled DLL for the site).

Aaaggghhh. Three hours later and it’s working. I’m still not sure if my understanding of the problem or it’s solution is correct but it’s working. And hopefully it will keep working.

No comments: