【发布时间】:2019-05-30 12:57:29
【问题描述】:
有一个工作示例: https://www.codeproject.com/Articles/3132485/CRUD-Operation-using-ASP-NET-CORE-2-2-and-React-Re
我想用配置中的字符串替换程序集中的硬编码连接字符串。它在原始示例中:
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;");
}
}
}
我已经添加了代码:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddDbContext<ContactDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString(nameof(ContactDBContext))));//<------?
//...
}
字符串读取正常,但未使用。仍然使用硬编码的字符串(参见第一段代码)。
我使用类似的上下文
public class ContactService : IContactService
{
public async Task<List<ContactModel>> GetContacts()
{
using (ContactDBContext db = new ContactDBContext())
{
//...
如何将连接字符串从应用程序传递到 EF 上下文?
【问题讨论】:
-
从
OnConfiguring中删除代码,该代码覆盖启动时设置的连接 -
您通过在
OnConfiguring中设置它来覆盖连接字符串,因为这发生在ConfigureServices之后。 -
啊,去掉代码还是去掉函数OnConfiguring?
-
也有可能因为你有一个默认构造函数,所以选项没有被传递给上下文,因此它将使用
OnConfiguring,因为在这种情况下没有配置生成器选项 -
我做了 2 次测试:删除 OnConfiguring 中的代码,删除函数,运行应用程序 - 同样的问题。
标签: c# asp.net-core entity-framework-core