Reputation: 6462
There is the working example: https://www.codeproject.com/Articles/3132485/CRUD-Operation-using-ASP-NET-CORE-2-2-and-React-Re
I'd like to replace the hardcoded connection string in assembly with string from config. It is in the original example:
public partial class ContactDBContext : DbContext
{
public ContactDBContext()
{
}
public ContactDBContext(DbContextOptions<ContactDBContext> options)
: base(options)
{
}
public virtual DbSet<Contacts> Contacts { get; set; }
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=yourservername ;
Database=ContactDB;Trusted_Connection=True;");
}
}
}
I have added the code:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddDbContext<ContactDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString(nameof(ContactDBContext))));//<------?
//...
}
The string is read ok, but it is not used. The hardcoded string still used (see the first piece of code).
I use the context like
public class ContactService : IContactService
{
public async Task<List<ContactModel>> GetContacts()
{
using (ContactDBContext db = new ContactDBContext())
{
//...
How to pass the connection string from app to EF context?
Upvotes: 4
Views: 8775
Reputation: 246998
Because you are manually creating the instance of the context, the configuration applied at startup is not being injected into the context and instead it is using the OnConfiguring
method.
That is why your configuration at start is not being applied.
Refactor the context to remove the default constructor and OnConfiguring
public partial class ContactDBContext : DbContext {
public ContactDBContext(DbContextOptions<ContactDBContext> options)
: base(options) {
}
public virtual DbSet<Contacts> Contacts { get; set; }
}
}
Next ensure that the context is injected into the desired dependent class
public class ContactService : IContactService {
ContactDBContext db;
public ContactService (ContactDBContext db) {
this.db = db
}
public async Task<List<ContactModel>> GetContacts() {
var contacts = db.Contacts;
//...convert to models
//...
}
}
The configuration applied at startup should now be included when the container resolves the context for injection.
Reference Configuring a DbContext
Upvotes: 4