如何从ASP.NET Core中的另一个类访问DataContext? [英] How do I access DataContext from another class in ASP.NET Core?

查看:186
本文介绍了如何从ASP.NET Core中的另一个类访问DataContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,以便可以查询我的数据.如果我在控制器类中执行此操作,则数据上下文有效,但如果在我创建的类中执行此操作,则会引发null错误.它将引发以下错误:

I created a class so I can query my data. If I do it in the controller class data context works, but if I do it in my created class it throws null error. It throws the following error:

Microsoft.Extensions.DependencyInjection.Abstractions.dll,但未在用户代码中处理

Microsoft.Extensions.DependencyInjection.Abstractions.dll but was not handled in user code

我的启动配置:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddDbContext<Abstractor_DataContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("ApplicationDatabase")));

    //services.AddTransient(typeof(Abstractor_DataContext));


    //Register your filter as a service (Note this filter need not be an attribute as such)
    services.AddTransient<AppExceptionFilterAttribute>();

    services.AddMvc();
}

我的类函数用于访问DataContext

My class function to access the DataContext

using Microsoft.Extensions.DependencyInjection;
public static IList<ApplicationInfo> TestDb()
{
    //var options = _serviceProvider.GetService<Abstractor_DataContext>();
    using (var context = _serviceProvider.GetService<Abstractor_DataContext>())
    {
        return context.ApplicationInfo.ToList();
    }
}

var context为空.我想念什么?我正在慢慢学习DI.

var context is null. What am I missing? I am slowly learning DI.

推荐答案

根据官方文档,首先,您需要创建模型和DbContext:

As per the official documentation for new DB based ASP.net core project, first you need to create your Models and DbContext:

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace EFGetStarted.AspNetCore.NewDb.Models
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }

        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}

然后,使用依赖项注入注册您的上下文:

Then, register your context with dependency injection:

public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;";
            services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

然后使用数据库迁移创建数据库.现在,使用构造函数将上下文作为参数之一来创建控制器(在构造函数参数中请注意BloggingContext context).

Then create your database using database migrations. Now you create your controller with your constructor taking your context as one of the parameter (Note BloggingContext context in the constructor parameter).

using EFGetStarted.AspNetCore.NewDb.Models;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace EFGetStarted.AspNetCore.NewDb.Controllers
{
    public class BlogsController : Controller
    {
        private BloggingContext _context;

        public BlogsController(BloggingContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(_context.Blogs.ToList());
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Blogs.Add(blog);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(blog);
        }

    }
}

在任何类中使用DbContext都与在控制器中使用它相同.您将需要向依赖注入器注册您的课程.它是通过ConfigureServices方法完成的. 官方文档中的此页面包含详细信息.以下是一些注册服务类实现的示例:

Using DbContext in any class is same using it in controller. You will need to register your class to Dependency injector. It is done in ConfigureServices method. This page from official docs is containing the details. Following are some of the examples to register the service class implementations:

services.AddScoped<ICharacterRepository, CharacterRepository>();
services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();

这篇关于如何从ASP.NET Core中的另一个类访问DataContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆