How do I programmatically set the connection string for Entity-Framework Code-First?

前端 未结 4 568
长发绾君心
长发绾君心 2020-11-27 16:27

I\'m trying to write some code that allows me to switch between SQLCE (locally on my dev machine) and full SQL (on AppHarbor). With SQL CE, the connection string is all hand

4条回答
  •  甜味超标
    2020-11-27 16:57

    You can also set it directly on your context. You have to attach the mdf to the SqlServer instance you want to use first. Not exactly elegant but it worked for me

    public void DoImportWork()
    {
       var ctx = new StatisticsContext(); << your DbContext 
    
       ctx.Database.Connection.ConnectionString = @"Data Source=localhost\SQLEXP;AttachDbFilename=""C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXP\MSSQL\DATA\StatisticsData.mdf"";Integrated Security=True";
    
       ctx.Database.Connection.Open();
    }
    

    as usual EF will auto-generate everything when you add your first row to the context.

提交回复
热议问题