У меня есть база данных SQL Server с EF Core в моем проекте, и я хочу добавить таблицу и столбец в другую таблицу. Но когда я запускаю add-migration < /code> в консоли PM, я получаю эту ошибку < /p>
An item with the same key has already been added. Key: MyProject.Model.MyContext
, где myproject - мой основной проект ASP.NET, а MyContext - мой класс dbContext. < /p>
Мой класс dbcontext выглядит как < /p>
namespace MyProject.Model
{
public class MyContext : DbContext
{
public MyWorker Worker { get; private set; }
///
/// initialize the worker instance to get the crud methods of the database
///
public MyContext()
{
Worker = new MyWorker(this);
}
public static string GetConnectionString()
{
return Startup.ConnectionString;
}
///
/// Our own context must override the OnConfiguring Method from Ef Core to set the right connection
/// Connectionstring is set in appsettings.json
///
///
protected override void OnConfiguring(DbContextOptionsBuilder _builder)
{
_builder.UseSqlServer(GetConnectionString());
}
protected override void OnModelCreating(ModelBuilder _modelBuilder) {
_modelBuilder.Entity().HasIndex(u => u.MailAdress).IsUnique();
}
public DbSet Projects { get; set; }
public DbSet Documents { get; set; }
public DbSet DocsData { get; set; }
public DbSet Users { get; set; }
public DbSet Systems { get; set; }
}
public class DesignTimeContextFactory : IDesignTimeDbContextFactory
{
public MyContext CreateDbContext(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder();
var connectionString = configuration["Connectionstrings:MyConnection"];
return new MyContext();
}
}
}
Таблица для добавления - это таблица Systems и два столбца, которые нужно добавить в документах Таблица.
с флагом -вербозе < /code> я получаю следующий выход < /p>
PM> Add-Migration Update -verbose
Using project 'MyProject'.
Using startup project 'MyProject'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.deps.json --additionalprobingpath C:\Users\chris\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.runtimeconfig.json C:\Users\chris\.nuget\packages\microsoft.entityframeworkcore.tools\2.2.4\tools\netcoreapp2.0\any\ef.dll migrations add Update --json --verbose --no-color --prefix-output --assembly D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.dll --startup-assembly D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.dll --project-dir D:\Development\Project\MyProject\MyProject\ --language C# --working-dir D:\Development\Project\MyProject --root-namespace MyProject
Using assembly 'MyProject'.
Using startup assembly 'MyProject'.
Using application base 'D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2'.
Using working directory 'D:\Development\Project\MyProject\MyProject'.
Using root namespace 'MyProject'.
Using project directory 'D:\Development\Project\MyProject\MyProject\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Found IDesignTimeDbContextFactory implementation 'DesignTimeContextFactory'.
Found DbContext 'MyContext'.
Found IDesignTimeDbContextFactory implementation 'DesignTimeContextFactory'.
Found DbContext 'MyContext'.
System.ArgumentException: An item with the same key has already been added. Key: MyProject.Model.MyContext
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextTypes()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextType(String name)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An item with the same key has already been added. Key: MyProject.Model.MyContext
Подробнее здесь: https://stackoverflow.com/questions/561 ... has-alread
Организация Entity Framework Core Add-Migration Throws «Элемент с той же ключом уже был добавлен. ⇐ C#
Место общения программистов C#
1738423523
Anonymous
У меня есть база данных SQL Server с EF Core в моем проекте, и я хочу добавить таблицу и столбец в другую таблицу. Но когда я запускаю add-migration < /code> в консоли PM, я получаю эту ошибку < /p>
An item with the same key has already been added. Key: MyProject.Model.MyContext
, где myproject - мой основной проект ASP.NET, а MyContext - мой класс dbContext. < /p>
Мой класс dbcontext выглядит как < /p>
namespace MyProject.Model
{
public class MyContext : DbContext
{
public MyWorker Worker { get; private set; }
///
/// initialize the worker instance to get the crud methods of the database
///
public MyContext()
{
Worker = new MyWorker(this);
}
public static string GetConnectionString()
{
return Startup.ConnectionString;
}
///
/// Our own context must override the OnConfiguring Method from Ef Core to set the right connection
/// Connectionstring is set in appsettings.json
///
///
protected override void OnConfiguring(DbContextOptionsBuilder _builder)
{
_builder.UseSqlServer(GetConnectionString());
}
protected override void OnModelCreating(ModelBuilder _modelBuilder) {
_modelBuilder.Entity().HasIndex(u => u.MailAdress).IsUnique();
}
public DbSet Projects { get; set; }
public DbSet Documents { get; set; }
public DbSet DocsData { get; set; }
public DbSet Users { get; set; }
public DbSet Systems { get; set; }
}
public class DesignTimeContextFactory : IDesignTimeDbContextFactory
{
public MyContext CreateDbContext(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder();
var connectionString = configuration["Connectionstrings:MyConnection"];
return new MyContext();
}
}
}
Таблица для добавления - это таблица Systems и два столбца, которые нужно добавить в документах Таблица.
с флагом -вербозе < /code> я получаю следующий выход < /p>
PM> Add-Migration Update -verbose
Using project 'MyProject'.
Using startup project 'MyProject'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.deps.json --additionalprobingpath C:\Users\chris\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.runtimeconfig.json C:\Users\chris\.nuget\packages\microsoft.entityframeworkcore.tools\2.2.4\tools\netcoreapp2.0\any\ef.dll migrations add Update --json --verbose --no-color --prefix-output --assembly D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.dll --startup-assembly D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2\MyProject.dll --project-dir D:\Development\Project\MyProject\MyProject\ --language C# --working-dir D:\Development\Project\MyProject --root-namespace MyProject
Using assembly 'MyProject'.
Using startup assembly 'MyProject'.
Using application base 'D:\Development\Project\MyProject\MyProject\bin\Debug\netcoreapp2.2'.
Using working directory 'D:\Development\Project\MyProject\MyProject'.
Using root namespace 'MyProject'.
Using project directory 'D:\Development\Project\MyProject\MyProject\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Found IDesignTimeDbContextFactory implementation 'DesignTimeContextFactory'.
Found DbContext 'MyContext'.
Found IDesignTimeDbContextFactory implementation 'DesignTimeContextFactory'.
Found DbContext 'MyContext'.
System.ArgumentException: An item with the same key has already been added. Key: MyProject.Model.MyContext
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextTypes()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextType(String name)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An item with the same key has already been added. Key: MyProject.Model.MyContext
Подробнее здесь: [url]https://stackoverflow.com/questions/56144823/entity-framework-core-add-migration-throws-an-item-with-the-same-key-has-alread[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия