我在NET Core2.0 App中有以下类.
// required when local database does not exist or was deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
public AppContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
}
}
Run Code Online (Sandbox Code Playgroud)
当Database不存在时,在Core 2.0中需要进行迁移,并且必须在运行update-database时创建.
升级到ASP.NET Core 2.0后无法创建迁移
我想在2个地方(这里和appsettings.json)没有ConnectionString,但只在.json,所以我试图更换
"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
Run Code Online (Sandbox Code Playgroud)
同
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我得到空值.
更新1:
请注意,在Core 2中明确添加.json是不必要的,所以问题不在于文件.
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/
更新2:
此外,我已经使用Configuration从.json向Context发送ConnectionString:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); …Run Code Online (Sandbox Code Playgroud) 我有一个项目类(Nuget Package).我需要在没有构造函数的静态类中读取我的连接字符串到MongoDB.
静态类方法:
/// <summary>
/// The default key MongoRepository will look for in the appsettings.json
/// </summary>
private const string DefaultConnectionstringName = "Data:MongoDB:MongoServerSettings";
/// <summary>
/// Retrieves the default connectionstring from appsettings.json
/// </summary>
/// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
public static string GetDefaultConnectionString()
{
var config = new Configuration();
return config.Get<string>(DefaultConnectionstringName);
}
Run Code Online (Sandbox Code Playgroud)
我总是null ...如何在不使用DI的情况下获取Startup.cs之外的值?
有可能的?
在我的旧代码中,我可以做类似的事情:
/// <summary>
/// Retrieves the default connectionstring from the App.config or Web.config file.
/// </summary>
/// <returns>Returns …Run Code Online (Sandbox Code Playgroud) 我正在研究 Web API Core 2.2,需要设计 3 层架构。我该怎么做。
我的项目结构如下
在 Web API 项目中..
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<HrmsDbContext>(opt =>
opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Run Code Online (Sandbox Code Playgroud)
在 DAL(图书馆项目,我制作了我的 DBContext 并提供了如下所示的连接字符串。
有没有更好的方法让我没有在两个地方提供连接字符串?并以良好的方式编写 3 层架构。
任何帮助将不胜感激。