【发布时间】:2020-01-02 01:53:32
【问题描述】:
项目结构如下:
汽车(ASP.NET Core MVC。这里有一个连接字符串)
Cars.Persistence(ASP.NET Core 类库。这里我们有 Repository,Database First)
我通过this msdn docs 的以下命令创建了一个模型:
Scaffold-DbContext "Server=PC\SQL2014XP;Database=Cars;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
到目前为止一切顺利。但是,现在carsContext 在Cars.Persistence - ASP.NET Core 类库中具有硬编码的连接字符串:
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
}
}
}
起初,我想在我的类库Cars.Persistence 中创建自己的appsettings.json。 However, according to this post it is not advisable to have appsettings.json file in Class Library..
I've read this approach,但是,如果我再次运行这个命令,硬编码的字符串会再次出现:
Scaffold-DbContext "Server=PC\SQL2014XP;Database=Cars;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
所以我的问题是如何在我的类库Cars.Persistence 中使用连接字符串(位于Cars 项目中)?
更新:
我已注释掉以下代码:
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=...");
}
}*/
}
【问题讨论】:
-
我对 Dapper 和 IDbConnection 类做了类似的事情。由于您使用的是 Core,因此您可以利用 IOptions 接口包装类并在启动时在组合根附近设置连接字符串。我已经有一段时间没有使用实体框架了,所以我的示例可能没有帮助,但你可以在 Github 上查看:github.com/B-Richie/Dapper_DAL
-
你让它比实际困难十亿倍!
-
@user10728126 你能说我怎么做更简单吗?
-
你有上面的例子或转到另一个线程:stackoverflow.com/questions/51304432/…
-
只需使用 Configuration 映射包含连接字符串的 appsettings.json 部分,并在启动时使用 IOptions 在组合根附近设置值。
标签: c# asp.net-core .net-core asp.net-core-mvc entity-framework-core