До миграции
Устройство имеет строковое свойство TenantId.
Миграция
Я представляю класс Tenant . У каждого устройства есть Тенант. Я меняю тип Device.TenantId со строки на int. Теперь это внешний ключ таблицы Tenant.
Вот код (классы и конфигурация контекста БД):
Код: Выделить всё
public abstract class Device
{
public int Id { get; set; }
public int TenantId { get; set; }
public Tenant Tenant { get; set; } // Navigation property
Код: Выделить всё
public class Tenant
{
public int Id { get; set; }
public string Name { get; set; }
public List Devices { get; set; } = []; // Navigation property
public List Lines { get; set; } = []; // Navigation property
public List Machines { get; set; } = []; // Navigation property
Код: Выделить всё
modelBuilder.Entity(builder =>
{
builder.ToTable("Devices").HasKey(d => new { d.Id });
builder.HasDiscriminator(d => d.DeviceType)
.HasValue(DeviceType.Machine)
.HasValue(DeviceType.Line);
builder.HasOne(device => device.Tenant)
.WithMany(tenant => tenant.Devices)
.HasForeignKey(device => device.TenantId);
});
modelBuilder.Entity(builder =>
{
builder.HasBaseType();
builder.HasOne(m => m.Line)
.WithMany(dl => dl.Machines)
.HasForeignKey(m => m.LineId);
builder.HasOne()
.WithMany(tenant => tenant.Machines)
.HasForeignKey(device => device.TenantId);
});
modelBuilder.Entity(builder =>
{
builder.HasBaseType();
builder.HasOne()
.WithMany(tenant => tenant.Lines)
.HasForeignKey(device => device.TenantId);
});
Когда я создаю миграцию, выводится:
Код: Выделить всё
The foreign key property 'Device.TenantId1' was created in shadow state because a conflicting property with the simple name 'TenantId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type. See https://aka.ms/efcore-relationships for information on mapping relationships in EF Core.
Код: Выделить всё
migrationBuilder.AlterColumn(
name: "TenantId",
table: "Devices",
type: "integer",
nullable: false,
defaultValue: 0,
oldClrType: typeof(string),
oldType: "text",
oldNullable: true);
migrationBuilder.AddColumn(
name: "TenantId1",
table: "Devices",
type: "integer",
nullable: true);
Я потерялся в этом вопросе, я работал над этой проблемой несколько раз. уже несколько часов, но я не могу найти решение.
Подробнее здесь: https://stackoverflow.com/questions/791 ... -migration