Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass connection string to code-first DbContext

How do I pass a connection string to entity framework's code-first DbContext? My database generation works correctly when both DbContext and the connection string in web.config is in the same project and named the same way. But now I need to move the DbContext to another project so I'm testing passing a connection string to it as follows:

Model & Context

public class Dinner {     public int DinnerId { get; set; }     public string Title { get; set; } }  public class NerdDinners : DbContext {     public NerdDinners(string connString)         : base(connString)     {     }     public DbSet<Dinner> Dinners { get; set; } } 

Action

    public ActionResult Index()     {         var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);          var dinners = (from d in db.Dinners                       select d).ToList();         return View(dinners);     } 

Web.Config

<connectionStrings>   <add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/>     </connectionStrings> 

If I set a breakpoint in the action an analyze the db, the connection string is there, but it does not create or find the database or anything.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

like image 254
Shawn Mclean Avatar asked Jan 26 '11 13:01

Shawn Mclean


People also ask

How do I change the connection string in Entity Framework?

If you want to change the connection string go to the app. config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.


1 Answers

A little late to the game here, but another option is:

public class NerdDinners : DbContext {     public NerdDinners(string connString)     {         this.Database.Connection.ConnectionString = connString;     }     public DbSet<Dinner> Dinners { get; set; } } 
like image 59
Bitfiddler Avatar answered Sep 25 '22 00:09

Bitfiddler