Entity Framework code first update-database fails on CREATE DATABASE

北城以北 提交于 2019-12-02 20:44:39
Sam

I found the answer here:

http://kazimnami.azurewebsites.net/techblog/2012/11/24/error-a-file-activation-error-occurred-create-database-failed/

Thank you kazim.

The exception is thrown when the "|DataDirectory|" property in the connection string is not evaluated. To solve the issue, add following line to your code:

AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());

Actually you need to put the line given by OP's answer in the extended xxContext: dbContext class.

public class WRContext : DbContext
{
    public WRContext()
        : base("localWR")
    {
        AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
    }
    public DbSet<Emp> Emps { get; set; }
    //....
}

If previous answer is right its easy to set it via command line

Update-Database -AppDomainBaseDirectory C:\you-path

For me the issue was that I moved from a (localdb) instance to a solid SQL server instance. In order to have update-database create the needed database i had to remove ;AttachDBFilename=|DataDirectory|\somedatabase.mdf

completely then everything else worked as expected

If your doing integration tests then use a generic controller method to set the directory. See StefanG's answer.

            public static T SetupController<T>() where T : ApiController, new()
            {
                //LocalDB database to the tests directory.
                AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());

                var request = new HttpRequestMessage();

                var config = WebApiConfig.SetupRegister(new HttpConfiguration());

                var controller = new T()
                {
                    Request = request,
                    Configuration = config
                };

                return controller;
            }

In my case it was just that the folder that it wanted to put the database files in didn't exist. Apparently visual studio can't create a directory for you for some reason.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!