首页 Enable-Migrations error

Enable-Migrations error

Enable-Migrations error

MVC数据迁移,ef 6.13 执行Enable-Migrations 则遇到以下异常信息 

PM> Enable-Migrations
System.BadImageFormatException: Could not load file or assembly 'Temp' or one of its dependencies. Index not found. (Exception from HRESULT: 0x80131124)
File name: 'Temp' ---> System.BadImageFormatException: Index not found. (Exception from HRESULT: 0x80131124)

   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.LoadAssembly(String name)
   at System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypeRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.GetContextType(String contextTypeName)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)

Could not load file or assembly 'Temp' or one of its dependencies. Index not found. (Exception from HRESULT: 0x80131124)

我要安装的就是Temp这个项目, 一般报以上异常就是dll未生成的原因,但是我项目我都运行起来了,,写了很多了,,怎么可能编译不通过呢,

Install-Package EntityFramework 未解决

一开始完全没头绪,网上各种搜索的解决办法都不对,因为网上的大多都是要么ef没安装, ef没安装输入Install-Package EntityFramework进行安装即可,

platform target 未解决

有的又是因为buildplatform targetX64改为Any Cpu即可,但是我的问题完全不是这些

复制文件 未解决

找了个把小时了,我想既然这个命令只是生成一个.cs文件,那我从测试项目copy过来好了,,但是我发现虽然可以copy过来,但是运行update-database一样是报错的,所以直接copy现成的文件肯定是不行的.

测试项目对比

但是项目文件已经有几十个了,,比较麻烦,所以我怀疑是不是我项目坏了,,新建一个测试项目安装也没问题,,

问题所在一:默认值搞的鬼

后来,在新建一个项目Temp把原来安装的项目里的文件一个个先放进来测试Enable-Migrations 然后终于花了几个小时试出来是因为我给一个字段设置了默认值,从而导致的不可以,我为了偷懒一般会给字段设置默认值如下

/// <summary>
/// 用户Id
/// </summary>
[Required]
public int UserId { get; set; } = 0;

这个默认值为0没啥问题,但是我有一个字段的默认值是通过另一个方法获取到的,如下

/// <summary>
/// Ip地址等信息
/// </summary>
[Required]
public string IpAndIsp { get; set; } = IpAddressHelper.GetClientIp();

本以为这个默认值去掉了就可以了,,但是结果还是不行原来还有一个默认值是有问题的

/// <summary>
/// 用以标示当前分页的唯一标示
/// </summary>
public long Id => Times.TimeStampWithMsec;

问题所在二:T

去掉了上面的还是不行,所以又花了一个小时找到了又一个问题

/// <summary>
/// 获取key对应的值
/// </summary>
/// <param name="key">key的长度不能超过100 否则反正异常</param>
/// <param name="lang"></param>
/// <returns></returns>
public static T GetConfigValue<T>(this string key, string lang = null) where T : class, new()
{
    key = key.ConfigKey();
    try
    {
        if (!ConfigDic.ContainsKey(key))
        {
            return !Refresh(key) ? null : ConfigDic[key].Value.DeserializeObjectByJson<T>();
        }
        var config = ConfigDic[key];
        if (!((DateTime.Now - config.ReadTime).TotalMinutes - config.RefreshTimeMin > 0)) return config.Value.DeserializeObjectByJson<T>();
        return !Refresh(key) ? null : ConfigDic[key].Value.DeserializeObjectByJson<T>();
    }
    catch (Exception)
    {
        return null;
    }
}

这段代码我把T去掉就可以,,,不知道为何 但是以上两个问题,我都不可能不存在,,所以打算弃用Enable-Migrations


Migrations

本来找了几个小时,都打算弃用了,,但是玩了会游戏,,突然还是想了想再搜了搜好像也没其他办法,,然后,果然成功了,,方法其实之前已经思考过了,但是被一个update-database的异常给弄的没使用,结果浪费了几个小时,

最终解决办法:如果在nuget使用Enable-Migrations会产生以上异常,则不用使用命令生成文件,该命令也只是在项目上添加一个目录Migrations并在目录下生成一个Configuration.cs文件而已,所以你可以直接把里面的代码复制到项目中

/// <summary>
/// 数据迁移
/// </summary>
public sealed class Configuration : DbMigrationsConfiguration<BlogContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;//允许数据迁移
        AutomaticMigrationDataLossAllowed = true;//允许迁移数据丢失
    }

    protected override void Seed(Kerwin.Blog.Repositories.Contexts.BlogContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

然后在Global.asax中的Application_Start添加以下一个操作即可

Database.SetInitializer(new MigrateDatabaseToLatestVersion());

关于上面构造函数中的AutomaticMigrationsEnabled以及AutomaticMigrationDataLossAllowed如果其中某个为false则当model改变的时候会产生以下的异常

AutomaticMigrationsEnabled = false;以下异常:Automatic migration was not applied because it would result in data loss. Set AutomaticMigrationDataLossAllowed to 'true' on your DbMigrationsConfiguration to allow application of automatic migrations even if they might cause data loss. Alternately, use Update-Database with the '-Force' option, or scaffold an explicit migration.

AutomaticMigrationsEnabled = true;AutomaticMigrationDataLossAllowed = false;以下异常:Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

如果在修改字段迁移的时候报错==数据库中已存在名为 'BlogArticle' 的对象==,那就是迁移失败导致的,因为我没有线上数据,所以删除重新运行即可,,,但是如果你的含有线上数据,不能删库,,可以尝试按照该人说的解决办法试试, 记得备份就是,,如果有相应的解决办法,,可以在下面回复或者以文章的形式在本站发布,以帮助更多的人 http://aehyok.com/Blog/Detail/101.html

数据库中已存在名为 'BlogArticle' 的对象。

总结就是人该能解决问题的时候,真的是什么都顺,,不该的时候啥都是背的。希望能够帮到你-_-

参考 :

  1. https://msdn.microsoft.com/en-us/data/jj591621

除另有声明外,本文章Enable-Migrations error采用 知识共享(Creative Commons) 署名-非商业性使用-相同方式共享 3.0 中国大陆许可协议 进行许可。

评论
目录