Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Specify connection string for api in EF5

I'm using the repository pattern using EF5 and I would like to specify the name of the connection string.

In my older EF projects I used to do this:

MyEntities _entities = new MyEntities("Name=MyConnectionString");

And when I created a new "api" that uses EF5 in VS2012 there is no overload for string argument.

I tried to do this:

private MyEntities _entities = new MyEntities ();

public MyRepository()
{
   _entities.Database.Connection.ConnectionString = "Name=MyConnectionString";
}

I get:

"No connectionstring named 'MyEntities' could be found in the application config file"

How should I give the repository a given connectionstring? Should I edit those code generation files?

Upvotes: 1

Views: 450

Answers (2)

Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Apparently the only thing needed was a partial class to make it work.

Here is how I did it...

public partial class MyEntities : DbContext
{
    public MyEntities(string connectionString) : base(connectionString) { }
}

After that I was able to use:

MyEntities _entities = new MyEntities("Name=MyConnectionString");

Upvotes: 1

Manish Mishra
Manish Mishra

Reputation: 12375

make your MyEntities constructor like:

 public MyEntities()
            : base("MyConnectionString")
 { 

 }

and a more generic way:

 public MyEntities(string connectionString)
            : base(connectionString)
        {
        }

assuming MyEntities class is the one which inherits DbContext

and use it like:

public MyRepository()
{
     using (MyEntities db = new MyEntities())
     {
     }

     //or
     using (MyEntities db = new MyEntities(connectionString))
     {

     }
}

Upvotes: 0

Related Questions