gpt4 book ai didi

c# - 如何从 ASP.NET Core 中的另一个类访问 DataContext?

转载 作者:行者123 更新时间:2023-11-30 14:49:21 25 4
gpt4 key购买 nike

我创建了一个类以便查询我的数据。如果我在 Controller 类数据上下文中这样做,但如果我在我创建的类中这样做,它会抛出空错误。它抛出以下错误:

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

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。

最佳答案

根据 official documentation对于新的基于 DB 的 ASP.net Core 项目,首先您需要创建模型和 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; }
}
}

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

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

然后使用数据库迁移创建您的数据库。现在,您使用将上下文作为参数之一的构造函数创建 Controller (注意构造函数参数中的 BloggingContext context)。

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 与在 Controller 中使用它是一样的。您需要将您的类(class)注册到依赖注入(inject)器。它是在 ConfigureServices 方法中完成的。 This page from official docs包含详细信息。以下是注册服务类实现的一些示例:

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>();

关于c# - 如何从 ASP.NET Core 中的另一个类访问 DataContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com