2 回答
TA贡献1818条经验 获得超8个赞
假设连接字符串设置在appsetting.json文件中。将文件添加到项目中
appsetting.json
{
"ConnectionStrings": {
"UserDatabase": "Server=DESKTOP-2K2A6GN;Database=Assignment4;Trusted_Connection=True;"
}
}
更新 DbContext 以便可以对其进行配置。
public class UserContext : DbContext {
public UserContext(DbContextOptions<UserContext> options): base(options) {
}
public virtual DbSet<User> tblUser { get; set; }
}
您将Startup在ConfigureServices方法的类中配置 DbContext 。
public class Startup {
public Startup(IHostingEnvironment env) {
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
static IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<UserContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("UserDatabase"));
);
//...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseBlazor<Client.Program>();
}
}
TA贡献1847条经验 获得超7个赞
您可以在文件 UserContext.cs 中更改
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public UserContext CreateDbContext(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
var builder = new DbContextOptionsBuilder<AppDbContext>();
var connectionString = configuration.GetConnectionString("UserDatabase");
builder.UseSqlServer(connectionString);
return new AppDbContext(builder.Options);
}
}
在文件 Startup.cs 中
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("UserDatabase"),
b => b.MigrationsAssembly("xxx.Data")));
}
- 2 回答
- 0 关注
- 368 浏览
添加回答
举报