如何在静态方法或控制器外的类中获取applicationDbContext的dbContext

时间:2018-03-03 16:06:24

标签: asp.net-mvc asp.net-core-mvc

当我在控制器外部的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?

当我处于局部视图中时,我想从服务器添加一些数据。 enter image description here

applicationdbcontext运行良好,但我无法在任何公共类中获得控制器 enter image description here

方法应该是这样的:获取当前的dbcontext,打开表,获取数据 enter image description here

1 个答案:

答案 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;