【发布时间】:2023-01-30 21:55:42
【问题描述】:
我正在构建一个带有简单 CRUD 操作的 ASP.NET Web Api 和一个应该使用 EF Code First 和迁移生成的数据库。 在项目结构方面,我使用 ASP.NET Web API 作为主项目,使用类库作为数据库上下文。
这是我的类库中的内容:
数据库上下文:
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 的类,它有一个应该为数据库播种的扩展方法
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"));
});
现在的问题是我想添加迁移。我转到包管理器控制台并导航到我的数据库上下文所在的类库项目。 然后我输入这个命令来添加一个迁移: dotnet ef 迁移添加“初始化” 然后会产生此错误: 无法创建“MyAppContext”类型的对象。对于设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728
我看过很多教程,但不幸的是,经过数小时的研究,我还没有找到可行的解决方案。
我在我的类库中使用 .net6 和以下 NuGet 包
- Microsoft.EntityFrameworkCore(版本 7.0.2)
- Microsoft.EntityFrameworkCore.SqlServer(版本 7.0.2)
- Microsoft.EntityFrameworkCor.Tools(版本 7.0.2)
如果有帮助,这是我的 connectionString:
{
"ConnectionStrings": {
"MyAppDb": "server=(LocalDB)\\mssqllocaldb;database=MyAppDB;integrated security=True"
}
}
【问题讨论】:
-
您是否注入了数据库上下文?
public void ConfigureServices(IServiceCollection services) => services.AddDbContext<MyAppContext>();查看错误消息附近帖子中的链接以获取详细信息。 -
@EricJ。是的,我做到了。实际上提供代码 ;) builder.Services.AddDbContext<MyAppContext>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("MyAppDb")); });
标签: c# entity-framework asp.net-web-api ef-code-first entity-framework-migrations