【发布时间】:2019-12-23 20:14:55
【问题描述】:
我正在尝试使用 Entity Framework Core。所以,在课程中。我搭建了现有的数据库对象。 因此,应用程序生成了包含所有 DBSet 对象的 EmployeeContext.cs 文件。然后它生成了 OnConfiguring() 重载方法。
现在我添加了以下代码 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
//options.AddPolicy("RequireManagerOnly", policy =>
// policy.RequireRole("Manager"));
options.AddPolicy(
"ApiUser", policy =>
policy.Requirements.Add(
new ApiUserVerification(5)));
});
services.AddSingleton<IAuthorizationHandler,
ApiRoleHandler>();
var connectionStrings = Configuration.GetConnectionString("DefaultConnections");
services.AddDbContext<EmployeeContext>(options => options.UseSqlServer(connectionStrings));
}
EmployeeContext.cs
public EmployeeContext()
{
}
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{
}
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 details");
}
}
但是现在,当我在上下文类中注释 OnConfiguring() 重载方法并从 POSTMAN 发布获取请求时,我收到 500-Internal Server Error。如果我取消注释 OnConfiguring(),我可以发布请求。 我不明白为什么?虽然我在 Startup.cs 中注册了 DbContext
谁能提供我失踪的地方。
谢谢
【问题讨论】:
-
您说的是 EmployeeContext.cs,但您使用的是 AddDbContext
。这是类的正确名称吗? -
@AntoniosKatopodis 用实际代码更新了帖子。我的问题是,当我使用脚手架时,我得到了两个 EmployeeContext 构造函数。你能解释一下原因吗?
标签: asp.net-core asp.net-core-2.1 ef-core-2.2