当我在控制器外部的asp.net核心类中工作时,例如从我的数据库表tbl_Notes获取一些记录,然后我需要一个_dbcontext或ApplicationDBContext来请求数据。
public static async Task<User_SumModel> get_User_Sums(ClaimsPrincipal parUser)
{
//------------< get_User_Sums(User) >------------
//*get User Summary Table
//return null;
if (parUser == null) return null;
ApplicationDbContext _dbContext = Common.DB.get_DbContext();
long sIDUser = await getIDUser_as_Number(parUser, _dbContext);
User_SumModel summary = await _dbContext.tbl_User_Sums.FirstOrDefaultAsync(u => u.IDUser == sIDUser);
return summary;
//------------</ get_User_Sums(User) >------------
}
但是如何在公共任务或共享类中获得_dbContext?
答案 0 :(得分:0)
您可以将ApplicationDbContext
传递给班级,并从IServiceProvider
创建新的作用域public class DataSeed
{
public static async Task InitializeData(IServiceProvider serviceProvider, bool createUsers = true)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var _context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
//use _context as your requirement
}
}
}
。
1.简单的代码如下:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
{
//seed init data
DataSeed.InitializeData(app.ApplicationServices).Wait();
}
2.拨打课程
.box2 {
width: 100px;
height: 100px;
position: absolute;
top: 50px;
left: 50px;
**background-color: rgba(255,255,255,0);**
border: solid blue 1px;
z-index: 4;