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?
OnConfiguringwhich is overriding the connection set at startupOnConfiguring, since that occurs afterConfigureServices.OnConfiguringbecause the builder options are not configured in that case