Entity Framework Code First DbContext Checks the ConnectionString During Compile?
It seems that the Code First DbContext really uses the given ConnectionString during compile? I don't even know how that is possible but to me it seems to be so. If I turn OFF my local SQL Server, I get the error stating "Faile开发者_高级运维d to get the MetadataWorkspace for the DbContext type...". Turning the SQL Server ON, everything compiles fine.
Here's part of my context (I'm using an existing database and yes, I know, not actually code first)
public class MyContext : DbContext
{
public MyContext() : base("MY_DYNAMIC_CONNECTIONSTRING")
{
Database.SetInitializer<MyContext>(null);
}
...
If this is really the case, there's a huge problem. How can I prevent it from doing that? What if I'm using separate build machines where the ConnectionString doesn't work? Or am I doing something wrong? Any advice?
WCF RIA Services instantiates a DbContext
at design time and build time, not only at runtime:
Quote from http://jeffhandley.com/archive/2011/06/30/RIAServicesCodeFirst.aspx:
In order to generate code into your Silverlight project, RIA Services has to inspect your DbContext at build time in order to get the entity types that are available.
Quote from http://varunpuranik.wordpress.com/2011/06/29/wcf-ria-services-support-for-ef-4-1-and-ef-code-first/#comment-102
The difference between EF CodeFirst stand alone and with RIA Services is that we initialize a new DbContext at design time as well.
If the connection string is not valid or the connection can't be established you apparently get the exception you mentioned.
Here is the way that I use to track down the root cause of the "Failed to get the MetadataWorkspace for the DbContext type '{type}'" error:
http://joshmouch.wordpress.com/2011/11/09/failed-to-get-the-metadataworkspace-for-the-dbcontext-type-type/
I know it doesn't specifically answer your question, but it could help others who search Google for this error message.
精彩评论