[英]Adding Migrations not working with EF Core Code first approach - C#
我正在構建一個 ASP.NET Web Api 的簡單 CRUD 操作和一個應該使用 EF Code First 和遷移生成的數據庫。 在項目結構方面,我使用 ASP.NET Web API 作為主項目,class 庫作為數據庫上下文。
這是我的 Class 庫中的內容:
數據庫上下文:
using Microsoft.EntityFrameworkCore;
using MyApp.Database.Models;
namespace MyApp.Database.Context;
public class MyAppContext : DbContext
{
public MyAppContext(DbContextOptions<MyAppContext> options) : base(options) { }
public virtual DbSet<Booking> Bookings { get; set; }
public virtual DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Seed();
base.OnModelCreating(modelBuilder);
}
}
數據庫模型:
namespace MyApp.Database.Models;
public class Booking
{
public int Id { get; set; }
public int Week { get; set; }
public int DayOfWeek { get; set; }
public int Hour { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
using System.Collections.Generic;
namespace MyApp.Database.Models;
public class Person
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public int Age { get; set; }
public virtual IEnumerable<Booking> Bookings { get; set; }
}
除此之外,我在名為 SeederExtension 的庫中有一個 class,它有一個應該為數據庫播種的擴展方法
using Microsoft.EntityFrameworkCore;
using MyApp.Database.Models;
namespace MyApp.Database;
public static class SeedExtension
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasData(new Person
{
Id = 1,
Firstname = "John",
Lastname = "Doe",
Age = 28,
});
}
}
在我的 ASP.NET Web API 項目中,我使用以下代碼在我的 Program.cs 中注冊了數據庫上下文。
builder.Services.AddDbContext<MyAppContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("MyAppDb"));
});
現在的問題是我想添加遷移。 我 go 到 Package 管理器控制台並導航到我的數據庫上下文所在的 Class 庫項目。 然后我輸入此命令以添加遷移:do.net ef migrations add "Init" 會產生此錯誤:無法創建類型為“MyAppContext”的 object。 有關設計時支持的不同模式,請參閱https://go.microsoft.com/fwlink/?linkid=851728
我看過很多教程,但不幸的是,經過數小時的研究,我還沒有找到可行的解決方案。
我在我的 class 庫中使用 .net6 和以下 NuGet 包
如果有幫助,這是我的 connectionString:
{
"ConnectionStrings": {
"MyAppDb": "server=(LocalDB)\\mssqllocaldb;database=MyAppDB;integrated security=True"
}
}
嘗試添加無參數構造函數: public MyAppContext() {}
。 選項將由 DI 根據 Startup class 中的 ConfigureService 傳遞給構造函數。“添加遷移”不應該知道要傳遞哪些選項,因為它不使用 Startup。
如果你看看這里
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects?tabs=do.net-core-cli
請注意您的命令和選擇數據庫 csproj 的區別。 在文檔中它有:
dotnet ef migrations add NewMigration --project WebApplication1.Migrations
連接字符串來自您的主項目。 同樣,來自文檔:
services.AddDbContext<ApplicationDbContext>(
options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("WebApplication1.Migrations")));
顯然,我剛剛從文檔中粘貼了上面的內容。 您將需要與自己的項目相匹配。
如果您改為僅使用數據庫項目運行遷移,我不確定它是否會從 web api 項目中提取連接字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.