Alex Rivera | Logout

ADO.NET Entity Connection String for Multiple Projects

Asked 2009-07-11T09:50:54.570
27

I am using multiple layer project where the DataModel hosts the ADo.NET Entity model and DataAccess layer does the validation.

However everytime I get a error like this

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

I have tried connection strings

<add name="SalesEntities" connectionString="metadata=res://*/SalesEntities.csdl|res://*/SalesEntities.ssdl|res://*/SalesEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.;Initial Catalog=Phoenix;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

and

<add name="SalesEntities" connectionString="metadata=.\SalesEntities.csdl|.\SalesEntities.ssdl|.\SalesEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.;Initial Catalog=Phoenix;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

also tried other combinations to refer the Root Directory of the Called project directory but no luck.

Any help is highly appreciated. Many Thanks as always :).

Edit
Report

1 Answer

2

I suggest a slight variation on the suggestions given above.

It's not a huge improvement, but at least it gives you some separation of concerns.

When the EF wizard creates the .edmx file and its associated .Designer.cs file, the C# code declares a partial class. So you can simply add another.cs file to the project containing the two EDM files.

This new file defines an additional static function for the same namespace and class.

This new static function will return an instance of the desired type (the descendant of ObjectContext).

The new file is a separate file, so it won't be overwritten if you re-create the .edmx and .Designer.cs.

You copy and paste the connection string from the .config of the EDM project, which is kind of a hack, but at least it keeps the connection string hidden in the EDM project.

The new file looks like this:

namespace MyNamespace
{
  public partial class MyEntities : ObjectContext
  {
    public static MyEntities New_MyEntities()
    {
      string connStr;
      MyEntities theContext;

      connStr = "metadata=res://*/MyClass.csdl|res://*/MyClass.ssdl|res://*/MyClass.msl;provider=System.Data.SqlClient;provider connection string=\"Data Source=localhost\\SQLSERVER;Initial Catalog=MyDb;Integrated Security=True;MultipleActiveResultSets=True\"";
      // set the connection string

      theContext = new MyEntities(connStr);
      // allocate it

      return theContext;
      // return it
    }
  }
}

To get a new entities object, you simply call the static function New_MyEntities() from your calling project.

answered 2010-12-28T19:44:44.653

Your Answer