我在尝试将Entity Framework Core的迁移添加到Code First项目时遇到错误,这里是详细信息......
我创建了一个新的ASP.Net Core Web项目(VS 2017中的Core 2.0)。它使用Microsoft.AspNetCore.All依赖项,如下所示:
我希望利用Entity Framework Core(我的理解是所有元数据都包含了EF Core依赖项,如下所示,看起来是正确的):
我已经设置了我的实体和上下文,并确保使用以下代码设置数据库。
示范模型
public class City
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(200)]
public string Description { get; set; }
}
示例上下文
public class CityInfoContext : DbContext
{
public DbSet<City> Cities { get; set; }
public DbSet<PointOfInterest> PointsOfInterest { get; set; }
public CityInfoContext(DbContextOptions options) : base(options)
{
Database.EnsureCreated();
}
}
Startup.cs配置
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddMvcOptions(options => {
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
})
.AddJsonOptions(options => {
if (options.SerializerSettings.ContractResolver != null)
{
var res = options.SerializerSettings.ContractResolver as DefaultContractResolver;
res.NamingStrategy = null;
}
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IMailService, LocalMailService>();
// Entity Framework services.
var connectionString = @"Server=(localdb)\mssqllocaldb;Database=CityInfoDB;Trusted_Connection=True;";
services.AddDbContext<CityInfoContext>(options => options.UseSqlServer(connectionString));
}
在我的控制器中使用此行初始化db conext:
public class DummyController : Controller
{
CityInfoContext _ctx;
public DummyController(CityInfoContext ctx)
{
_ctx = ctx;
}
}
我可以看到db已经成功创建 - 到目前为止一切都很好。
我想使用此命令拍摄我的数据库的快照: PM&GT;添加迁移CityInfoInitialMigration
但是得到错误: 项目'CityInfo.API'上未安装EntityFramework包。
有没有人遇到过这个?我明确尝试添加EF包,但这也不起作用!
答案 0 :(得分:6)
NPM> Get-Module
如果结果包含EntityFramework
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 6.0.0.0 EntityFramework {Add- EFDefaultConnectionFactory, Add-EFProvider, Add-Migration, Enable-Migrations...}
Script 2.0.0 EntityFrameworkCore {Add-Migration, Drop-Database, Enable-Migrations, Get-DbContext...}
Script 2.0.0.0 NuGet {Add-BindingRedirect, Find-Package, Get-Package, Get-Project...}
Script 0.0 profile
意味着EntityFrameworkCore
和EntityFramework
Nuget包安装在项目中并导致
未安装EntityFramework包
在我的情况下,我引用了一些引用EntityFramework 6.0.0
的Nuget包(因此EntityFramework
包被引用间接)。删除该包后,错误已得到修复。
查找此类引用的最简单方法是使用Search Solution Explorer
对话框
答案 1 :(得分:2)
确保已安装Microsoft.EntityFrameworkCore.Tools程序包。该软件包定义了EF Core的PMC命令。
答案 2 :(得分:1)
就我而言,我安装了 Microsoft.EntityFrameworkCore.SqlServer
答案 3 :(得分:0)
我能够通过以下文章使用命令行界面解决此问题:
https://docs.microsoft.com/en-gb/aspnet/core/data/ef-mvc/migrations#introduction-to-migrations
答案 4 :(得分:-1)