Compiler error using EF4 as a separate project tha

2019-08-27 02:22发布

问题:

I'm trying to follow the general consensus that it's best to put one's domain objects in a separate project than their MVC project, but am getting the following compiler error:

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

Source File: C:\Users\Kevin\documents\visual studio 2010\Projects\HandiGamer\HandiGamer.Domain\Entities\HGDomainModel.Designer.cs Line: 44

Line 42:         /// Initializes a new HGEntities object using the connection string found in the 'HGEntities' section of the application configuration file.
Line 43:         /// </summary>
Line 44:         public HGEntities() : base("name=HGEntities", "HGEntities")
Line 45:         {
Line 46:             this.ContextOptions.LazyLoadingEnabled = true;

I'm a bit confused, as HGEntities is there in the entity's App.Config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="HGEntities" connectionString="metadata=res://*/Entities.HGDomainModel.csdl|res://*/Entities.HGDomainModel.ssdl|res://*/Entities.HGDomainModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\HandiGamer.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

Do I need to add the connection to my MVC Web.Config or something?

回答1:

Yes you need to add it to your MVC Web.Config file.

Since you have an ASP.Net MVC project in place, the connection string must be present in the web.config of your MVC project where the runtime will be looking to find it. Basically any connection string should be in the config file of your executable project (i.e. where the .Net threads started from by CLR). So just copy and paste the whole connection string into your web.conig and you're done!