ALTER TABLE ALTER COLUMN ObjID не удалось, потому что один или несколько объектов обращаются к этому столбцу - PullRequest
0 голосов
/ 05 мая 2020

Сначала в коде Entity Framework я просто изменил столбец первичного ключа char с char(41) на char(42) с помощью консольной команды dotnet ef migrations add ChangedObjIDLen. Это создало следующий очень простой скрипт обновления:

using Microsoft.EntityFrameworkCore.Migrations;

namespace DE.ZA.MobilePickingApp.Migrations
{
    public partial class ChangedObjIDLen : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterColumn<string>(
                name: "ObjID",
                table: "CustomFields",
                type: "char(42)",
                maxLength: 42,
                nullable: false,
                oldClrType: typeof(string),
                oldType: "char(41)",
                oldMaxLength: 41);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterColumn<string>(
                name: "ObjID",
                table: "CustomFields",
                type: "char(41)",
                maxLength: 41,
                nullable: false,
                oldClrType: typeof(string),
                oldType: "char(42)",
                oldMaxLength: 42);
        }
    }
}

Вот код класса:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace DE.ZA.MobilePickingApp.Model.Database {
    public class CustomFields {
        [Key, StringLength(42, MinimumLength = 42), Column(TypeName = "char(42)"), JsonIgnore]
        public string ObjID { get; set; }

        public bool ItemInProcess { get; set; }

        public string Remarks { get; set; }

        public bool Retrieved { get; set; }

        public bool Commissioned { get; set; }


        [NotMapped]
        private static readonly Dictionary<string, PropertyInfo> _EditableFields;

        static CustomFields() {
            _EditableFields = typeof(CustomFields)
                .GetProperties()
                .Where(p => p.Name != "ObjID")
                .ToDictionary(p => p.Name.ToLower(), p => p);
        }

        public static bool IsFieldEditable(string fieldName) {
            return _EditableFields.Keys.Contains(fieldName.ToLower());
        }

        internal void SetValue(KeyValuePair<string, object> entry) {
            PropertyInfo p;

            if (!_EditableFields.TryGetValue(entry.Key.ToLower(), out p))
                throw new ArgumentException("Invalid key");

            p.SetValue(this, entry.Value);
        }
    }
}

Однако, как только я попытаюсь применить эту миграцию к базе данных, используя dotnet ef database update, Я получаю следующую ошибку:

Объект PK_CustomFields зависит от столбца ObjID. ALTER TABLE ALTER COLUMN ObjID завершился неудачно, поскольку один или несколько объектов обращаются к этому столбцу.

Как я могу избавиться от этого?

...