The structure of projects looks like this:
Cars (ASP.NET Core MVC. Here we have a connection string)
Cars.Persistence (ASP.NET Core Class library. Here we have Repository, Database First)
I've created a Model by the following command from this msdn docs:
Scaffold-DbContext "Server=PC\SQL2014XP;Database=Cars;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
So far so good. However, now carsContext
has hard coded connection string in Cars.Persistence
- ASP.NET Core Class library:
public partial class carsContext: DbContext
{
public carsContext()
{
}
public carsContext(DbContextOptions<carsContext> options)
: base(options)
{
}
public virtual DbSet<Cars> Cars { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=PC\SQL2014XP...");// hard coded
// connection string
}
}
}
At first, I thought to create own appsettings.json
in my class library Cars.Persistence
. However, according to this post it is not advisable to have appsettings.json
file in Class Library..
I've read this approach, however, the hard coded string will appear again, if I will run this command again:
Scaffold-DbContext "Server=PC\SQL2014XP;Database=Cars;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
So my question is how can I use connection string(located in Cars
project) in my class library Cars.Persistence
?
UPDATE:
I've commented out the following code:
public partial class eshopContext : DbContext
{
public eshopContext(DbContextOptions<eshopContext> options): base(options)
{}
// public eshopContext(){}
/*protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=...");
}
}*/
}