I have a developer that is getting «Build failed.» when running add-migration in a .NET Core EF project, with no explanation of why the build failed. How do you troubleshoot this error?
This is what he gets in the Package Manager Console:
Additional information:
We have a few other developers using the same solution code (myself included) that have not issues with add-migration.
This is what I see in Package Manager Console:
We’ve verified that the project builds, and the entire solution builds. We’ve done «dotnet restore» and rebuild all multiple times, in addition to restarting VS2015. We’ve verified that the correct default solution is selected both in Solution Explorer, and in the Package Manager Console drop-down. We’ve verified that he has the correct SDK installed on his machine. I’m at a loss as to what to check next…any time I’ve had a failure during add-migration I’ve gotten enough information to point me in the direction of what to check, but just «Build failed.» is a fairly useless error output.
asked Jun 27, 2017 at 16:33
8
It’s because of other projects in your solutions. e.g If you have two projects in your solution as Project A and Project B. If Project A is not successful build and then Project B data migration will fail. So you should unload Project A and add the migration to Project B again.
I think this is not a good answer but hope this help.
![]()
lets do it
22.9k18 gold badges92 silver badges180 bronze badges
answered Sep 4, 2017 at 16:06
mmh18mmh18
1,5152 gold badges11 silver badges11 bronze badges
3
I had the exact same problem (.NET Core 2.0.1).
Sometimes it helps if the project is rebuilt.
I also encounter the problem when I opened the project in 2 Visual Studios.
Closing one Visual Studio fixed the error.
- Ctrl + C (first stop the application from running, this alone might be enough!)
- dotnet run build
- dotnet ef migrations add InitialCreate
answered Dec 12, 2017 at 15:19
![]()
MaklaMakla
9,57115 gold badges69 silver badges138 bronze badges
3
I was struggling with this one while using Visual Studio 2019 version 16.5.0.
What solved it finally:
- Close Visual Studio;
- Reopen Visual Studio;
- Make sure you right click the Solution if you have multiple projects and select
Rebuild Solution.
Note that I tried doing a Rebuild Solution before and that did not catch the error. So it’s important to close VS and reopen it.
It then showed the error that was causing add-migration command to fail with Build failed message.
answered Mar 17, 2020 at 17:29
Leniel MaccaferriLeniel Maccaferri
98.9k44 gold badges363 silver badges467 bronze badges
1
I suggest adding -v to have more info.
In my example, I had to add
<LangVersion>latest</LangVersion> to my projects, as this was missing from some of them.
answered Apr 12, 2019 at 8:49
Try these steps:
-
Clean the solution.
-
Build every project separately.
-
Resolve any errors if found (sometimes, VS is not showing errors until you build it separately).
-
Then try to run migration again.
![]()
Pang
9,335146 gold badges85 silver badges121 bronze badges
answered Nov 26, 2018 at 13:23
0
In my situation it was the error
namespace aspnetcore does not exist .. are you missing a reference?
I have figured it out by adding the -v (or —verbose) flag to the dotnet ef command.
answered Apr 21, 2018 at 21:09
![]()
Liam KernighanLiam Kernighan
2,2471 gold badge21 silver badges23 bronze badges
1
In my case, the application was running. Apparently, it needs to be stopped. Weird error message anyways.
![]()
Pang
9,335146 gold badges85 silver badges121 bronze badges
answered May 9, 2019 at 18:08
![]()
Denis NutiuDenis Nutiu
93814 silver badges21 bronze badges
2
Had the same situation.
This helped:
-
Open Package Manager Console
-
Change directory to Migrations folder:
cd C:YourSolutionYourProjectWithMigrations -
Enter in PM:
dotnet ef migrations add YourMigrationName
![]()
Pang
9,335146 gold badges85 silver badges121 bronze badges
answered Feb 2, 2018 at 9:15
YaroslavYaroslav
4746 silver badges13 bronze badges
Open Output window in Visual Studio and check your build log. In my case, even though my current configuration was Release, Add-Migration built the project in Debug, which had an error. For some reason, VS didn’t display the error anywhere except Output window for me.
![]()
Pang
9,335146 gold badges85 silver badges121 bronze badges
answered Jun 28, 2018 at 8:28
ArchegArcheg
8,2826 gold badges40 silver badges88 bronze badges
2
Got the same error when I tried to run add-migration. Make sure that you don’t have any syntax errors in your code.
I had a syntax error in my code, and after I fixed it, I was able to run add-migration.
![]()
Fourat
2,3162 gold badges40 silver badges53 bronze badges
answered Dec 8, 2019 at 17:29
Sara OnvalSara Onval
1141 silver badge4 bronze badges
1
Most likely that there is an existing error in your code. Try rebuilding first and correct all the errors.
Happened to me, I am trying to rollback migration but I have not corrected the errors in the code yet.
answered Jul 30, 2018 at 10:53
![]()
0
Just got into this issue.
In my case, I was debugging my code and it was making my migrations fail.
Since in Visual Studio Code, the debugger is so low-profile (only a small bar), I didn’t realize about this until I read some questions and decided to look better.
![]()
Pang
9,335146 gold badges85 silver badges121 bronze badges
answered Apr 25, 2019 at 14:58
andrescpachecoandrescpacheco
5341 gold badge7 silver badges24 bronze badges
I had exact same error but I am using Visual Studio Community 2017 Version 15.2 (26430.14) to build .Net Core projects.
I have a ASP.NET Core MVC web project and a separate security project using ASP.NET Core Identity. The web project contains connection string in aspsettings.json config file.
I also installed Bundler & Minifier and Web Essentials 2017 extensions in Visual Studio so that I can compile, minify and bundle my assets and put them to wwwroot.
I figured out it was the MSBuild those 2 extensions secretly download that caused the problem, because I had Enable Bundle on Build and Enable Compile on Build on. After I disable that, everything works fine.
Probably not the cause to your problem, but might be worthy to just give it a try.
answered Jun 29, 2017 at 22:59
![]()
David LiangDavid Liang
19.6k6 gold badges42 silver badges67 bronze badges
I think this happened to me when I tried to run dotnet ef migrations add xyz whilst it was already running.
In the end, just to be sure, I stopped the currently running instance, then ran it again to ensure it was rebuilt, stopped it again and I was able to run the dotnet ef migrations add command
answered Apr 19, 2018 at 15:40
ec2011ec2011
5706 silver badges20 bronze badges
In My case, add the package Microsoft.EntityFrameworkCore.Tools fixed problem
answered Aug 20, 2020 at 15:03
Try saving DataContext.cs first. It worked for me.
![]()
Pang
9,335146 gold badges85 silver badges121 bronze badges
answered Oct 4, 2018 at 20:12
The developer ended up un-mapping the project from TFS, deleting it, and re-mapping it. It’s now working for him.
answered Jun 27, 2017 at 21:38
jceddyjceddy
1,5972 gold badges11 silver badges18 bronze badges
1
I think the 2 commands below always work (if you run them at project’s folder)
- dotnet ef migrations add (database object fron ApplicationDbContextDBContext)
- dotnet ef database update
answered Jun 29, 2018 at 10:24
gbarelgbarel
711 silver badge8 bronze badges
I had the same error. What I did, I corrected the error the one I have in code, and rebuilt the project. Then I ran the ms-dos command and it worked.
answered Aug 27, 2018 at 17:23
I got the same error. There were no errors during the build proccess. I closed the Visual Studio and it worked.
answered Aug 16, 2019 at 11:54
![]()
Imran ShImran Sh
1,4934 gold badges30 silver badges46 bronze badges
I had the same problem when running:
dotnet ef migrations add InitialCreate
so what I did is tried to build the project using:
dotnet build command.
It throws an error : Startup.cs(20,27): error CS0103: bla bla for example. which you can trace to find the error in your code.
Then i refactored the code and ran:
dotnet build again
to check any errors until there is no errors and build is succeded.
Then ran:
dotnet ef migrations add InitialCreate
then the build succeded.
answered Dec 20, 2019 at 10:51
![]()
this is because deleting projects or class libraries from solution and adding projects after deleting with same name.
best thing is delete solution file and add projects to it.this works for me
(I did this using vsCode)
answered Apr 29, 2020 at 16:19
![]()
pamal Sahanpamal Sahan
4213 silver badges7 bronze badges
In my case I had couple of such errors:
The process cannot access the file 'C:xxxbinDebugnetcoreapp3.1yyy.dll'
because it is being used by another process. [C:zzz.csproj]
I was able to see those errors only after adding -v parameter.
The solution was to shutdown the Visual Studio and run the command again.
answered Aug 27, 2020 at 13:00
infografnetinfografnet
3,5791 gold badge33 silver badges33 bronze badges
1
I faced the same error. The issue in my case was that I was running my backend server with the watch build and since .Net Build was overburdened, it was unable to execute the add migration command at the same time, therefore I had to stop running the application and then run the migration command again.
answered Jun 21, 2022 at 4:53
![]()
maybe it cause because of you did not add this in YOUR_PROJECT.csproj
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.Dotnet" Version="2.0.2" />
answered Jul 28, 2018 at 3:27
Make sure you have code generation inside startup.cs
Example
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.3" />
</ItemGroup>
</Project>
answered Jun 4, 2019 at 11:41
![]()
I got the same error. I fixed it by stopping the project build. After that it worked fine.
answered Aug 9, 2019 at 10:31
lrefopamlrefopam
4711 gold badge4 silver badges18 bronze badges
Turns out this could also be caused by BuildEvents. For me I was referencing $(SolutionDir) there. With a regular build this variable has value, but running dotnet * commands is done at project level apparently. $(SolutionDir) comes out like Undefined in verbose mode (-v). This seems like a bug to me.
answered Dec 5, 2019 at 9:33
![]()
petkopetko
1431 silver badge13 bronze badges
1: I was getting the error:
PM> Add-Migration «InitialDB»
Build failed.
2:The error was the «(» missing. I corrected that and error is gone.
so the error you can see the error in the output. The error was because of the code issue.
answered Dec 8, 2019 at 9:50
ManiMani
3272 silver badges10 bronze badges
In my case it was failing because an unrelated project in the solution was failing. Unloading that project and running the command again worked.
answered Jan 16, 2020 at 3:17
Pranav RajPranav Raj
7411 gold badge8 silver badges19 bronze badges

- Remove From My Forums
-
Question
-
User887623398 posted
Hi
I run this command on package manager console :
pm>add-migration FirstAppDemo
but keeping <g class=»gr_ gr_100 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace» id=»100″ data-gr-id=»100″>get</g> this image:
The project first app demo failed to build.
What should I do?
please inform.
regards
Saeed
All replies
-
User887623398 posted
Thanks for your reply.
I’m afraid my entity framework and sql configuration is correct in start up.cs.
Here comes my configuration:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var sqlconnection = "Data Source=(localdb)\mssqllocaldb;Initial Catalog=FirstAppDemo"; services.AddDbContext<FirstAppDemoDbContext>(dbcontextoption => dbcontextoption.UseSqlServer(sqlconnection)); }Would you please let me know if any thing is wrong?
-
User-369506445 posted
It’s not depended to your config
According to your error, I said first build your project and sure you do not get any error
If your project become build success
Then
- Run the Enable-Migrations command in Package Manager Console . (make sure that default project is the project where your context class is)
Next Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was
created -
User887623398 posted
I built my project and there is no error.
In <g class=»gr_ gr_20 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace» id=»20″ data-gr-id=»20″>microsoft</g> documentation comes to this command:
Add-Migration InitialCreate
and when I write and run this command after a while this error comes which is highlighted:
Object reference not set to an instance of an object.
please inform.
-
User1528429020 posted
Having the same problem, if you found any solution please help
PM> add-migration AddBooleanPurposeColumnsToCustomersTable
The project ‘CustomersDemo’ failed to build.
By Jason Groce – https://github.com/dotnet/docs/blob/cb475ed45f881e9462e34764480d3b0ebce85e91/docs/images/hub/netcore.svg, Public Domain, Link
The new .NET Core 3.0 was released on September 23, 2019, with lots of new features and new changes. Often times, those new changes will not cause any trouble but sometimes they do. And there is one specific change in this new update that will give you a headache if you update to .NET Core 3.0 without reading what has been changed in the new release, and this change is related to the “dotnet ef” command-line tool.
Starting in .NET Core 3.0, the “dotnet ef” command-line tool is removed from the .NET Core SDK. If you updated your .NET Core SDK to the latest version and when you execute EF Core migration or scaffolding commands, you will get the following error:
Could not execute because the specified command or file was not found.
Possible reasons for this include:
- You misspelled a built-in dotnet command.
- You intended to execute a .NET Core program, but dotnet-ef does not exist.
- You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
The fix to this error is to manually install the “dotnet-ef” command-line tool by running the following command:
To install the tool as a global tool:
dotenet tool install --global dotnet-ef --version 3.0.0
It is optional to specify the version in the command. If you want to install the tool as a local tool, just remove “–global” option in the above command.
![]()
In this article, I will show you how to use AJAX PopupControlExtender to build a multiple select DropDownList as this: Firstly, we […]

I have a habit of keeping my computer system as up-to-date as possible, including Windows updates and hardware drivers, so when I noticed […]
![]()
Browser has a handy feature that remembers the information entered earlier in text boxes, and this feature can save you a lot […]
![]()
Any time you use Remote Desktop Connection to connect to another computer, the name or the IP address of the connected computer […]
Управление схемой БД и миграции
Данное руководство устарело. Актуальное руководство: Руководство по Entity Framework Core 7
Последнее обновление: 15.11.2020
Если мы меняем модели в Entity Framework, которые входят в контекст данных, например, добавляем в нее какие-то новые свойства или удаляем некоторые
свойства, то необходимо, чтобы база данных также применяла эти изменения. Например, в прошлых темах был создан класс User, который описывал пользователя:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
А для работы с базой данных использовался следующий контекст данных:
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public ApplicationContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)mssqllocaldb;Database=helloappdb;Trusted_Connection=True;");
}
}
Допустим, мы хотим добавить в класс User новое свойство, например:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Position { get; set; } // Новое свойство - должность пользователя
}
И если у нас уже ранее была создана база данных, на которую указывает строка подключения в классе контекста, и мы попытаемся выполнить какие-нибудь
операции с моделью User, то мы столкнемся с ошибкой.

Так как модель User изменилась, то нам надо привести в соответствие соответствующую таблицу в БД. В зависимости от конкретной ситуации можно использовать ряд подходов для этого.
Ручное изменение базы данных
В самых простых случаях мы можем написать sql-скрипт для добавления столбцов или таблиц, либо же даже можем вручную в режиме дизайнера таблицы в Visual
Studio добавить столбцы и/или таблицы. Для этого перейдем к дизайнеру таблицы:


Например, свойству Position с типом string будет соответствовать столбец Position с типом NVARCHAR. После добавления столбца нажмем на кнопку Update и
далее на кнопку Update Database:

В итоге будет добавлен новый столбец. И теперь таблица Users находится в соответствии с классом User. Больше никаких проблем при выполнении программы не возникнет.
Теоретически и практически так можно делать. Стоит отметить, что при этом мы максимально контроллируем процесс изменения базы данных. Все данные,
которые у меня были в таблице, так там и остались.
Тем не менее этот подход имеет много недостатков. В частности, менее искушенные программисты могут не знать, как сопоставляются типы между SQL и C#. При указании данных
столбцов и/или таблиц мы можем допустить ошибку — например, вместо «Position» написать «Positon». В конце концов такой подход может занять много времени,
особенно когда речь идет о куда больших изменениях схемы БД.
Database.EnsureCreated и Database.EnsureDeleted
Другой очень простой способ изменения схемы данных представляет применение пары методов Database.EnsureCreated и
Database.EnsureDeleted, которые определены в классе контекста. Database.EnsureCreated создает базу
данных, а Database.EnsureDeleted удаляет ее.
Первый метод уже ранее использовался для создания бд в конструкторе контекста данных. Подобным образом можно вызвать оба метода:
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public ApplicationContext()
{
Database.EnsureDeleted(); // удаляем бд со старой схемой
Database.EnsureCreated(); // создаем бд с новой схемой
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)mssqllocaldb;Database=helloappdb;Trusted_Connection=True;");
}
}
То есть мы сначала удаляем базу данных со старой схемой, а потом создаем ее заново.
Преимуществом этих методов является то, что мы можем вызвать их в любом месте приложения, создав объект контекста.
В то же время при удалении происходит полное удаление данных, что в ряде случаев может быть нежелательным. И в этом случае лучше использовать
миграции.
Миграция
Миграция по сути предствляет план перехода базы данных от старой схемы к новой. Как использовать миграции?
Для создания миграции в окне Package Manager Console вводится следующая команда:
Add-Migration название_миграции
Название миграции представляет произвольное название, главное чтобы все миграции в проекте имели разные названия.
После создания миграции ее надо выполнить с помощью команды:
Update-Database
Если планируется использовать миграции, то лучше их использовать сразу при создании базы данных.
Для использования миграций в Visual Stuido необходимо добавить в проект через менеджер Nuget пакет Microsoft.EntityFrameworkCore.Tools.
Например, определим модели и контекст следующим образом:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public ApplicationContext()
{
// Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)mssqllocaldb;Database=userappdb;Trusted_Connection=True;");
}
}
Обратите внимание, что в конструкторе контекста закомментирован метод Database.EnsureCreated(). В данном случае он не нужен.
Более того при выполнении миграции этот метод вызывает ошибку. Этот момент следует учитывать.
Теперь для создания и выполнения миграции перейдем в Visual Studio к окну Package Manager Console. Вначале введем команду
Add-Migration InitialCreate
Название миграции произвольное. В данном случае это InitialCreate. Нажмем на Enter для создания миграции.
После этого в проект будет добавлена папка Migrations с классом миграции:

Папка содержит три файла:
-
XXXXXXXXXXXXXX_InitialCreate.cs: основной файл миграции, который содержит все применяемые действия
-
XXXXXXXXXXXXXX_InitialCreate.Designer.cs: файл метаданных миграции, которые используются Entity Frameworkом
-
[Имя_контекста_данных]ModelSnapshot.cs: содержит текущее состояние модели, используется при создании следующей миграции
В частности, мы можем открыть файл, который в названии содержит имя миграции, и посмотреть те действия, которые будет применяться:
using Microsoft.EntityFrameworkCore.Migrations;
namespace HelloApp.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Age = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}
В миграции определяются два метода: Up() и Down(). В методе Up с помощью вызова метода CreateTable
добавляется новое определение таблиц.
И в завершении чтобы выполнить миграцию, применим этот класс, набрав в той же консоли команду:
Update-Database

После выполнения миграции мы найдем сгенерированную базу данных. Следует отметить, что кроме основных таблиц (в случае выше таблицы Users) база данных
также будет содержать дополнительную таблицу _EFMigrationsHystory, которая будет хранить информацию о миграциях.
Если мы изменим модель, например, добавим в класс User новое свойство:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool IsMarried { get; set; }
}
Чтобы база данных соответствовала измененной модели, также создадим новую миграцию и выполним ее:
Add-Migration IsMarriedToUserAdded Update-Database
В данном случае будет создан класс миграции, который отражает добавление нового свойства в класс User:
using Microsoft.EntityFrameworkCore.Migrations;
namespace HelloApp.Migrations
{
public partial class IsMarriedToUserAdded : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsMarried",
table: "Users",
type: "bit",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsMarried",
table: "Users");
}
}
}
Метод AddColumn как раз добавляет новый столбец в таблицу.
Миграции в консоли
Если разработка осуществляется не в Visual Studio, то для миграций мы можем выполнять соответствующие команды в консоли. Для создания миграции:
dotnet ef migrations add InitialCreate
Для выполнения миграции:
dotnet ef database update
Метод Migrate
В некоторых случаях, например, в приложениях с локальной базой данных (SQLite в UWP), мы можем выполнять миграции в процессе выполнения приложения. Для этого определен метод Database.Migrate(),
который можно вызвать через объект контекста:
myDbContext.Database.Migrate();
Стоит учитывать, что перед вызовом этого метода не следует вызывать метод EnsureCreated, который обходит миграции при создании базы данных, что
вызывает ошибку при выполнении метода Migrate.
Чтобы задействовать этот метод, необходимо подключить пространство имен Microsoft.EntityFrameworkCore
Миграция, если конструктор контекста принимает параметр DbContextOptions
Выше была рассмотрена миграция для контекста данных, который имеет конструктор без параметров и устанавливает настройки подключения в методе
OnConfiguring(). Однако мы можем также передавать параметры подключения в контекст данных извне через конструктор с параметром типа DbContextOptions:
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
{
}
}
Например, у нас в проекте есть файл конфигурации appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)mssqllocaldb;Database=helloappdb32;Trusted_Connection=True;"
}
}
Из которого в процессе выполнения приложения мы извлекаем строку подключения и передаем в контекст данных:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Linq;
namespace HelloApp
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
// установка пути к текущему каталогу
builder.SetBasePath(Directory.GetCurrentDirectory());
// получаем конфигурацию из файла appsettings.json
builder.AddJsonFile("appsettings.json");
// создаем конфигурацию
var config = builder.Build();
// получаем строку подключения
string connectionString = config.GetConnectionString("DefaultConnection");
var optionsBuilder = new DbContextOptionsBuilder<ApplicationContext>();
var options = optionsBuilder
.UseSqlServer(connectionString)
.Options;
using (ApplicationContext db = new ApplicationContext(options))
{
var users = db.Users.ToList();
foreach (User u in users)
{
Console.WriteLine(u.Name);
}
}
}
}
}
Как получать конфигурацию подключения из файла, описывалось в статье Конфигурация подключения
При выполнении миграции для такого контекста данных мы получим ошибку:
PM> Add-Migration InitialCreate Build started... Build succeeded. Unable to create an object of type 'ApplicationContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Дело в том, что, если единственный конструктор класса контекста принимает параметр DbContext:
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options){ }
В этом случае при выполнении миграции инструментарий Entity Frameworkа ищет класс, который реализует интерфейс IDesignTimeDbContextFactory
и который задает конфигурацию контекста.
Поэтому в этом случае нам необходимо добавить в проект подобный класс. Например:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
namespace HelloApp
{
public class SampleContextFactory : IDesignTimeDbContextFactory<ApplicationContext>
{
public ApplicationContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationContext>();
// получаем конфигурацию из файла appsettings.json
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json");
IConfigurationRoot config = builder.Build();
// получаем строку подключения из файла appsettings.json
string connectionString = config.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(connectionString, opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds));
return new ApplicationContext(optionsBuilder.Options);
}
}
}
Класс SampleContextFactory применяет интерфейс IDesignTimeDbContextFactory, который типизируется типом контекста данных — в данном случае класс ApplicationContext.
Данный интерфейс содержит один метод CreateDbContext(), который должен возвращать созданный объект контекста данных.
В данном случае также получаем конфигурацию из файла appsettings.json и извлекаем из ее строку подключения и таким образом создаем контекст.
Хотя этот класс формально нигде не вызывается и никак не используется, фактически он вызывается инфраструктурой Entity Framework при создании миграции.
Add-Migration initial -v Build started Build failed or Update-Database Failed
Solution:
- Make sure the solution is building right, clean and rebuild, if any project fails, fix it.
- Use dot net tool through command prompt to add the migration it will give you clear information
dotnet ef migrations add MigrationName -v
Now fix the issue, in my case I needed to add reference to Microsoft.EntityFrameworkCore.Design
So I installed Microsoft.EntityFrameworkCore.Tools and it fixed the issue.

if still looking for answers check this post
Happy Coding!
Published by scientistz
Zaheer is Microsoft CertifiedTrainer MCT. He is an azure solutions architect along with SharePoint Developer/Admin having years of Microsoft products experience essentially in development. He is also Microsoft Certified Azure Solution Architect Expert(MCSE) and Microsoft Certified Solution Developer App Builder(MCSD). He loves to help others and make a change in the world and this blog is the one of ways, He uses to influence people.
View all posts by scientistz