Как решить проблему при сохранении объекта в БД?

В БД PostgresSql была связь Таблица1-Таблица2. Я решил изменить ссылку одной таблицы на другую - дропнул внешний ключ, дропнул поле, создал новое поле и внешний ключ, теперь связь Таблица1 - Таблица3.

Сделал изменения в модели. Было:

public class Table1
{
    [Key]
    [Column("id")]
    public Guid Id { get; set; }
 
    [Column("id_table2")]
    public int TABLE2_Id { get; set; }
    public TABLE2 value { get; set; }
}

стало:

public class Table1
{
    [Key]
    [Column("id")]
    public Guid Id { get; set; }
 
    [Column("id_table3")]
    public int TABLE3_Id { get; set; }
    public TABLE3 value { get; set; }
}

Но теперь при сохранении объекта в БД, вылазит Exception такого типа, что он пытается вставить значение в поле "TABLE2", которого уже нет в БД:

fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
          Failed executing DbCommand (16ms) [Parameters=[@p0='?' (DbType = Guid), @p1='?' (DbType = Int32), @p2='?' (DbType = Int32), @p3='?' (DbType = Gu
          INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
          VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
          INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
          VALUES (@p6, @p7, @p8, @p9, @p10, @p11);
          INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
          VALUES (@p12, @p13, @p14, @p15, @p16, @p17);
          INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
          VALUES (@p18, @p19, @p20, @p21, @p22, @p23);
    !!! Failed executing DbCommand (16ms) [Parameters=[@p0='?' (DbType = Guid), @p1='?' (DbType = Int32), @p2='?' (DbType = Int32), @p3='?' (DbType = Guid
    INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
    VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
    INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
    VALUES (@p6, @p7, @p8, @p9, @p10, @p11);
    INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
    VALUES (@p12, @p13, @p14, @p15, @p16, @p17);
    INSERT INTO public.access_cell (id, "limit", id_schedule_attribute, "ScheduleId", time_to_end, time_to_start)
    VALUES (@p18, @p19, @p20, @p21, @p22, @p23);
    fail: Microsoft.EntityFrameworkCore.Update[10000]
          An exception occurred in the database while saving changes for context type 'N3.Schedule.Providers.Linq2db.Data.N3ScheduleDbContext'.
          Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
           ---> Npgsql.PostgresException (0x80004005): 42703: столбец "ScheduleId" в таблице "access_cell" не существует
             at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMo
             at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
             at Npgsql.NpgsqlDataReader.NextResult()
             at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
             at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
             at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
             at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
             at System.Data.Common.DbCommand.ExecuteReader()
             at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
             at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConn!!! An error occurred while updating the entrie
    ection connection)
            Exception data:
              Severity: ОШИБКА
              SqlState: 42703
              MessageText: столбец "ScheduleId" в таблице "access_cell" не существует
              Position: 69
              File: d:\pginstaller_12.auto\postgres.w!!! +- 42703: столбец "ScheduleId" в таблице "access_cell" не существует
    indows-x64\src\backend\parser\parse_target.c
              Line: 1034
              Routine: checkInsertTargets
             --- End of inner exception stack trace ---
             at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
             at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
             at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
             at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
             at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
             at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Fun
             at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
             at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)

Ответы (1 шт):

Автор решения: Scrim

У тебя не правильно записан внешний ключ, по соглашению он должен быть Table3Id, то есть <Название класса><Название ключа класса, или просто ID>, или можешь пометить сущность параметром [ForeignKey]. Так-же не уверен что ты сделал миграцию бд, то есть не обновил её, чтобы изменения вступили в силу.

→ Ссылка