我正在尝试在ASP.NET项目中使用显式事务。调试时,只要达到使用行(var transaction = ...) 抛出以下异常:
“没有为'Microsoft.Data.Entity.Storage.IRelationalConnection'类型的服务注册”
我在下面列出了我的依赖项。我在启动文件中遗漏了什么吗?
using (ApplicationDbContext context = new ApplicationDbContext())
{
try
{
using (var transaction = context.Database.BeginTransaction())
{
//do some work
}
}
catch (Exception exc) { }
}
我的依赖项:
"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final" }
由于
答案 0 :(得分:0)
您收到此错误,因为ApplicationDbContext尚未配置为使用特定提供程序。有几种方法可以将DbContext配置为指向您的数据库,如EF Core官方文档中Configuring a DbContext中所述。
例如,
public class ApplicationDbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlite("Filename=./test.db");
}
}
或者如果你想使用依赖注入,
// in Startup.cs
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite("Filename=./test.db"));
// in a constructor argument
public HomeController(ApplicationDbContext context)
...
// in code
using(var context = serviceProvider.GetRequiredService<ApplicationDbContext>())
....