这是一个工作示例:https://www.codeproject.com/Articles/3132485/CRUD-Operation-using-ASP-NET-CORE-2-2-and-React-Re
我想使用配置中的字符串替换程序集中的硬编码连接字符串。在原始示例中,它是这样的:
如何将连接字符串从应用程序传递给EF上下文?
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
方法中删除覆盖启动时设置的连接的代码。 - NkosiOnConfiguring
中设置连接字符串会在ConfigureServices
之后发生,因此您正在覆盖连接字符串。 - Heretic MonkeyOnConfiguring
,因为在这种情况下构建器选项未配置。 - Nkosi