[英]unable to create an object of type 'applicationdbcontext'. For the different patterns supported at design time error
[英]Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time
我在.net核心添加數據庫遷移時遇到如下錯誤
這是錯誤:
這是Startup
中的代碼:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
這是ApplicationDbContext
class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
這是ApplicationUser
用戶:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
我發現此錯誤的原因可能是您的代碼中的多個問題。 至少對我來說,最好的方法是在命令中添加詳細信息。
有了這個就可以理解是什么問題了。 verbose
將顯示執行的所有步驟。
在視覺工作室使用:
add-migration Added_something -verbose
對於 CLI 使用:
dotnet ef migrations add Added_something --verbose
如果選擇了多個啟動項目,也會出現此錯誤。 我將我的 webproject 設置為啟動項目,這為我解決了這個問題。
通過安裝Microsoft.EntityFrameworkCore.Design
nuget 包解決了我的問題。
這個包是Entity Framework Core Tools工作所必需的。 確保您的啟動項目是正確的。然后安裝包。
最后Build -> Clean Solution在您的項目中,然后嘗試再次運行您的命令。
添加遷移命令 cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
更新數據庫命令 cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
刪除遷移命令 cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
我今天在運行dotnet ef migrations add <MigrationName>
時也遇到了同樣的問題
我有三個項目,MainApp (Web)、帶有 DBContext 的 C# 項目和用於模型的 C# 項目。
我能夠從 CLI 解決它。
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
如果從 .net 核心應用程序的 Program.cs 中刪除static IHostBuilder CreateHostBuilder(string[] args)
方法,也會發生此錯誤。 (這是我的情況)
看來你是你的繼承是錯誤的。
public ApplicationDbContext : IdentityDbContext
應該
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
或者
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
如果您還擴展角色類。
當您想使用擴展用戶類(而不是IdentityUser
)創建上下文時
當我有兩個 DbContext 構造函數時,我遇到了同樣的錯誤。 在重新排列構造函數順序后,無參數構造函數是類中的第一個修復它。 例如
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
它必須是動態 DbContext 對象調用和反射在這里播放的東西。
我嘗試了許多上述答案,但沒有一個對我有用。 我的問題是我們有多個啟動項目,所以這是第一步。 只需設置一個啟動項目,所以我將我們的Data
項目設置為啟動。 仍然得到錯誤。 然后它擊中了我(感謝@AFetter 的回答) Data
項目中沒有連接字符串。 因此,我將我的啟動項目設置為一個帶有與數據庫連接的appSettings.json
文件的項目,然后確保將包管理器控制台的默認項目設置為Data
項目並重新運行命令以創建遷移並且它工作!
如果您在使用 .Net 6 和新的最小托管模型時遇到此問題,請在調用builder.services
上的AddDbContext
之前檢查您是否未調用builder.build()
。
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
我發現我不見了:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
我有多個啟動項目(不同的 API)。 我在 PM 控制台中處於不同的級別。 然后我了解到我必須關閉 SQL 管理才能運行 PM 控制台命令。
從 azure 管道任務運行 dot net ef migrations script 命令時,我遇到了同樣的問題。 我確實添加了“-project”參數。 但還是失敗了。 添加“-startup-project”參數對我有用。 我想即使我們在 project 中指定了啟動類,但要讓 ef 工具找到一個我們必須明確提及它們。
閱讀這篇文章: https ://docs.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
該工具嘗試使用各種方法創建設計時數據庫上下文實例。 其中一種方法是尋找IDesignTimeDbContextFactory
的實現。
某些 EF Core 工具命令(例如,遷移命令)需要在設計時創建派生的 DbContext 實例,以便收集有關應用程序實體類型以及它們如何映射到數據庫架構的詳細信息。 在大多數情況下,希望由此創建的 DbContext 以類似於在運行時的配置方式進行配置。
以下是您的 DB 上下文工廠類的外觀:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
盡管 OP 面臨的問題似乎是由於錯誤使用 AspNet Identity 提供的基類,但通常我們會在設計時無法創建 ApplicationDbContext 的實例時遇到此錯誤。 有幾個解決方案。 其中之一是在 StartUp 類的 ConfigureServices 方法中指定 ApplicationDbContext 提供程序:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
有關其他解決方案,請查看此鏈接: https ://docs.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
我遇到了同樣的錯誤......除了代碼在幾分鍾前工作正常。 我正在用Fluent API
替換一些屬性屬性
我有三個項目:WebApp、DataAccess Library 和 Model Library。
在嘗試了一些不成功的遷移操作之后……我最終做了一個Build->Clean Solution
並在 WebApp 上進行了構建。 一切都在工作......我無法重新創建錯誤。
這個錯誤發生在我身上,但同時我An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
修復我的appsettings.json
文件解決了這個問題。
我有同樣的錯誤,只是修改程序類。 網核3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
至
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
就我而言,這是因為我將數據類型和遷移存儲在單獨的“數據”項目中,並且不小心將其設置為啟動項目,而不是我的實際啟動項目。
就我而言,我在 appsettings.json 中缺少一個顯示為警告而不是錯誤的屬性
此錯誤消息有時與 db 上下文模型沒有直接關系。 檢查 Startup 類中的其他錯誤,例如 appsettings.json/appsettings.Development.json 中缺少屬性/憑據
使用 --verbose 選項運行遷移以查看所有錯誤和警告
dotnet ef migrations add YourMigrationName --verbose
得到同樣的錯誤...
這是我到達那里的方式:
創建了一個新的 ASP.NET Core Web 應用程序(模型-視圖-控制器)
目標框架是 .NET Core 3.1 (LTS)
認證類型:個人賬戶
創建項目后...我希望能夠修改注冊/登錄過程。(但這些頁面是 Razor 類庫的一部分)
所以要獲取項目中的頁面:我右鍵單擊項目Add->New Scaffolded Item...
並選擇了Identity
...
接下來我需要Add-Migration InitIdentity
...這就是錯誤/問題開始的地方。
我嘗試閱讀和解決其他一些答案,但沒有成功。
我通過以下方式找到了解決方案:
創建項目,如(上)
但這一次我決定不支持身份。(還)
我在application.config
中放置了一個連接字符串並運行了該項目。
我在添加遷移之前這樣做了。
我進去注冊...出現一個屏幕,說遷移尚未運行,並且有一個按鈕來運行遷移。 我按下它並進行了刷新,一切都很好。
在這一點上,我回到項目並做了一個Add->Scafolded Item...
現在沒有錯誤,我有 Auth 屏幕要修改。
徹底檢查您的 appsettings 文件並確保其格式正確。 查找丟失的字符或不必要的字符
就我而言,我使用的是自定義IdentityErrorDescriber
:
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
在我的MyIdentityErrorDescriber
中,我使用資源來翻譯錯誤。 當我注釋掉.AddErrorDescriber<MyIdentityErrorDescriber>()
行時,遷移工作沒有任何錯誤。 我認為問題出在IdentityErrorDescriber
或資源上。
我有三個項目,一個是 Api,第二個是 Models,第三個是 ApplicationDbContext。 Api 項目正在啟動項目。 我已將Microsoft.EntityFrameworkCore.Design nuget 包添加到 Api 項目(它是啟動項目)並解決了問題。
我遇到了同樣的錯誤,當我添加它時它工作正常:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
如果您使用的是 Docker-Compose 項目。 您需要卸載 Docker-Compose 項目,然后清理並重建解決方案並設置啟動項目。
在 EFCore 中創建遷移對我很有用。
我在應用程序設置文件中有兩個連接字符串配置,都缺少逗號來分隔兩者。 當我輸入逗號時,錯誤消失了。
這可能不是您的問題,但這就是導致我出錯的原因。 如果您的應用在構建時加載環境變量,則應在終端中聲明該變量。 就我而言,我的應用程序從 json 文件加載了我的GOOGLE_APPLICATION_CREDENTIALS
。 在運行與構建相關的任何內容之前,我需要導出該變量。
就我而言,我構建了我的項目並且它工作。 因此,請嘗試先完成這個簡單的步驟。
強文本我在.Net 6中遇到了同樣的問題確保AddDBContext在builder.Build之上
builder.Services.AddDbContext<DatabaseDBContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
在 Program.cs 文件中,不要在var app = builder.Build()行下方使用 builder.Services.... 寫入任何內容,否則會出錯。
以供將來參考,一個簡單的陷阱,以前有過我。
確保您的 appsettings.json 文件中的連接字符串中確實有一個值。
IE
這將引發錯誤:
"ConnectionStrings": {
"ConnectionString": ""
},
這不會:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
就我而言,當我從教程存儲庫復制項目時發生此錯誤。 我設法通過 NuGet 包管理器更新項目包來解決它。
我發現在我的 ApplicationDbContext 中執行以下操作為我解決了這個問題:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer("Server=(LocalDB)\\MSSQLLocalDB;Database={DbName};Trusted_Connection=True;MultipleActiveResultSets=True");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
這似乎確實因用戶而異。
在我的例子中,我想從我的類庫項目創建遷移。
安裝的 Nuget 包:
public class RandomDataContext : DbContext
{
public virtual DbSet<YourCustomModel> YourCustomModels { get; set; }
public RandomDataContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("your_connection_string");
}
}
在包管理器控制台中運行后:
dotnet ef migrations add InitialMigration --project YourProjectName
然后
dotnet ef database update --project YourProjectName
我有這個問題
當我解決它時,我的數據庫就創建好了。
以我為例,在 MS Visual Studio2022.Net 6 中重新安裝 NuGET 軟件包
Microsoft.EntityFrameworkCore 版本 6.0.12
Microsoft.EntityFrameworkCore.Design 版本 6.0.12
Microsoft.EntityFrameworkCore.SqlServer 版本 6.0.12
Microsoft.EntityFrameworkCore.Tools 版本 6.0.12
改變我的 DbContext..
using Leagues.Models.Domains;
using Microsoft.EntityFrameworkCore;
namespace Leagues.Models.Context {
public partial class FifaDbContext:DbContext {
public FifaDbContext()
{
}
public FifaDbContext(DbContextOptions options):base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<League> Leagues { get; set; }
public virtual DbSet<Club> Clubs { get; set; }
public virtual DbSet<Point> Points { get; set; }
}
}
確認我的 AppSettings
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"FiFa": "Data Source=DESKTOP-R34I8VP;Initial Catalog=FiFaWorldCup;Integrated Security=True;"
}
}
確認程序.cs
using Leagues.Models.Context;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var ConnectionStrings = builder.Configuration.GetConnectionString("FiFa");
builder.Services.AddDbContext<FifaDbContext>(option => option.UseSqlServer(ConnectionStrings));
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
添加遷移
更新數據庫
我遇到了同樣的問題,出現此錯誤的原因有很多,但就我而言,是因為刪除了program.cs class(早於 do.net 6 的 startup.cs)中的某些內容,我刪除了
builder.Services.AddControllersWithViews();
不小心將其添加到我的 class 時錯誤已修復 我希望這對您有所幫助
就我而言,我不得不刪除舊的快照和遷移。 我采取的步驟是:
當我忘記在 Startup.cs 中執行此操作時,我遇到了此錯誤。
services.AddTransient<IExcelMasterRepository, ExcelMasterRepository>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.