@DenisVladimirovich

Как сделать обновление миграции EFCore?

Доброго вечера господа. Подскажите пожалуйста. Делаю проект небольшой и столкнулся с проблемой. После того как я первый раз удачно сделал Update-Migration и в базе создались таблицы, я попробовал просто добавить поле в модель и обновить базу данных. EFCore постоянно выдает что таблица уже существует. Но изменения то есть. Он получается вместо alter table выполняет create table. В чем может быть моя ошибка? Код к сожалению выложить не могу физически.

spoiler
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (28ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Product] (
[ProductId] int NOT NULL IDENTITY,
[ProductTitle] nvarchar(max) NULL,
[ProductDescription] nvarchar(max) NULL,
[Category] nvarchar(max) NULL,
[PrductPrice] int NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY ([ProductId])
);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Users] (
[UserId] int NOT NULL IDENTITY,
[Login] nvarchar(max) NULL,
[Name] nvarchar(max) NULL,
[LastName] nvarchar(max) NULL,
[Email] nvarchar(max) NULL,
[Password] nvarchar(max) NULL,
[Phone] nvarchar(max) NULL,
[RegID] int NOT NULL,
[UserRole] int NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY ([UserId])
);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Department] (
[DepartmentID] int NOT NULL IDENTITY,
[DepartmentTitle] nvarchar(max) NULL,
[UserForeignKey] int NULL,
CONSTRAINT [PK_Department] PRIMARY KEY ([DepartmentID]),
CONSTRAINT [FK_Department_Users_UserForeignKey] FOREIGN KEY ([UserForeignKey]) REFERENCES [Users] ([UserId]) ON DELETE NO ACTION
);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Post] (
[PostID] int NOT NULL IDENTITY,
[PostTitle] nvarchar(max) NULL,
[PostImage] nvarchar(max) NULL,
[PostDescription] nvarchar(max) NULL,
[PostText] nvarchar(max) NULL,
[PostDS] datetime2 NOT NULL,
[PostKeyWords] nvarchar(max) NULL,
[PostMetaDesc] nvarchar(max) NULL,
[PostedByUserId] int NULL,
CONSTRAINT [PK_Post] PRIMARY KEY ([PostID]),
CONSTRAINT [FK_Post_Users_PostedByUserId] FOREIGN KEY ([PostedByUserId]) REFERENCES [Users] ([UserId]) ON DELETE NO ACTION
);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (10ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Deal] (
[DealID] int NOT NULL IDENTITY,
[ParentDealID] int NOT NULL,
[ChildNumber] int NOT NULL,
[DealDS] datetime2 NOT NULL,
[DepartmentForeignKey] int NULL,
[UserForeignKey] int NULL,
[ProductForeignKey] int NULL,
CONSTRAINT [PK_Deal] PRIMARY KEY ([DealID]),
CONSTRAINT [FK_Deal_Department_DepartmentForeignKey] FOREIGN KEY ([DepartmentForeignKey]) REFERENCES [Department] ([DepartmentID]) ON DELETE NO ACTION,
CONSTRAINT [FK_Deal_Product_ProductForeignKey] FOREIGN KEY ([ProductForeignKey]) REFERENCES [Product] ([ProductId]) ON DELETE NO ACTION,
CONSTRAINT [FK_Deal_Users_UserForeignKey] FOREIGN KEY ([UserForeignKey]) REFERENCES [Users] ([UserId]) ON DELETE NO ACTION
);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE INDEX [IX_Deal_DepartmentForeignKey] ON [Deal] ([DepartmentForeignKey]);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE INDEX [IX_Deal_ProductForeignKey] ON [Deal] ([ProductForeignKey]);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE INDEX [IX_Deal_UserForeignKey] ON [Deal] ([UserForeignKey]);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE UNIQUE INDEX [IX_Department_UserForeignKey] ON [Department] ([UserForeignKey]) WHERE [UserForeignKey] IS NOT NULL;
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE INDEX [IX_Post_PostedByUserId] ON [Post] ([PostedByUserId]);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]');
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId];
Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20190724114851_InitialCreate'.
Applying migration '20190724114851_InitialCreate'.
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Product] (
[ProductId] int NOT NULL IDENTITY,
[ProductTitle] nvarchar(max) NULL,
[ProductDescription] nvarchar(max) NULL,
[Category] nvarchar(max) NULL,
[PrductPrice] int NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY ([ProductId])
);
В базе данных уже существует объект с именем "Product".


Тут я заметил, а может и не правильно заметил, но создание таблица Product происходит два раза. В начале и в конце.
  • Вопрос задан
  • 815 просмотров
Решения вопроса 1
@Free_ze
Пишу комментарии в комментарии, а не в ответы
При каждом изменении моделей и/или их связей, нужно сначала сгенерировать очередную миграцию (Add-Migration), а затем - накатить изменения на схему (Update-Database).

В CLI будет так:
dotnet ef migrations add NewMigrationName;
dotnet ef database update;


Подробнее читать тут.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы