Reputation: 1036
My project structure is pretty standard:
within EFData
.
EFData
is an Entity Framework Core class library that isolates all of the database interaction. Database models, and my DBContext
. I built it that way so that it's database environment agnostic.
The API project of course has a reference to EFData
.
How do I pass the connection string from Startup.cs
in API
to DBContext.cs
in EFData
?
I've read multiple articles that reference a set up different than mine where I might expect a Startup.cs
in my EFData
project. I don't have that.
Within Startup.cs
, I do have what I thought was the required line -
services.AddDbContext<DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
But EFData
knows nothing about that connection string.
Upvotes: 2
Views: 9643
Reputation: 305
Steps to Get Connection and build your database
your connection string looks good just make sure your database connection string is correct.
Here is a link if you need more information
Upvotes: 0
Reputation: 91
One approach can be adding a ConnectionString property in the DBContext.cs class and then setting it on the startup.cs of the API project explicitly. Add the following code in DBcontext.cs
using System;
using System.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public class DBContext
{
public static void SetConnectionString(string connectionString)
{
if (ConnectionString == null)
{
ConnectionString = connectionString;
}
else
{
throw new Exception();
}
}
// this part will help you to open the connection
public static SqlConnection OpenConnection()
{
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
return connection;
}
private static string ConnectionString { get; set; }
//add the connectionString to options
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
}
}
Now, in the API project add a reference of the EFData project and in the startup.cs file set the ConnectionString
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var connectionString = this.Configuration.GetConnectionString("DBName");
Namespace.DBContextContext.SetConnectionString(connectionString); //replace namespace with the namespace suitable for your solution
//here goes rest of your default code
}
This way you should be able to access the Connection in your API project.
Upvotes: 3