Hi, Using the below web api GET method with entity framework. Currently the class SchoolDBEntities() connects to DEV database. How do I change the connectionstring when the API gets moved up to QAT, Pre-PROD & PROD. Is there a way to change it from the web.config file?
public class StudentController : ApiController
{
public IHttpActionResult GetAllStudents ()
{
IList<StudentViewModel> students = null;
using (var ctx = new SchoolDBEntities())
{
students = ctx.Students.Include("StudentAddress")
.Select(s => new StudentViewModel()
{
Id = s.StudentID,
FirstName = s.FirstName,
LastName = s.LastName
}).ToList<StudentViewModel>();
}
if (students.Count == 0)
{
return NotFound();
}
return Ok(students);
}
}
What I have tried:
I have tried to use the code below. But couldn't get it working.
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
dataContext = new SampleEntities(ecb.ConnectionString);
public class SingleConnection
{
private SingleConnection() { }
private static SingleConnection _ConsString = null;
private String _String = null;
public static string ConString
{
get
{
if (_ConsString == null)
{
_ConsString = new SingleConnection { _String = SingleConnection.Connect() };
return _ConsString._String;
}
else
return _ConsString._String;
}
}
public static string Connect()
{
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = "SQLSERVER\\DEV".ToString(),
InitialCatalog = "TestDB",
UserID = "devuser",
Password = "devpassword",
};
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
Metadata = "res://*/DevModel.csdl|res://*/DevModel.ssdl|res://*/DevModel.msl",
ProviderConnectionString = @"data source=SQLSERVER\DEV;initial catalog=TestDB;user id=devuser;password=devpassword"
};
return entityString.ConnectionString;
}
}