0

Не могу изменить первичный ключ в модели наследуемой от IdentityUser в ASP.NET MVC. Я создаю только условного IdentityUser, без кастомных ролей и не могу никак поменять тип создаваемого Первичного Ключа, возникает ошибка из-за несоответствия Первичного и Внешнего ключей.

При создании миграции выдаёт ошибку:

The relationship from 'Club.AppUser' to 'AppUser.Clubs' with foreign key properties {'AppUserId' : int?} cannot target the primary key {'Id' : string} because it is not compatible. Configure a principal key or a set of foreign key properties with compatible types for this relationship.

Когда навожу на Id в классе AppUser выдаёт:

AppUser.id скрывает наследуемый член Identity< string >.id. Чтобы текущий член перевыполнял операцию добавите ключевое слово override

и это тоже пробовал.

Буду очень благодарен за любую помощь.

Части кода для понимания проблемы:

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class AppUser : IdentityUser
    {
        [Key]
        public int Id { get; set; }
        public int? Pace { get; set; }
        public int? Mileage { get; set; }
        public string? ProfileImageUrl { get; set; }
        public string? City { get; set; }
        public string? State { get; set; }
        [ForeignKey("Address")]
        public int? AddressId { get; set; }
        public Address? Address { get; set; }
        public ICollection<Club> Clubs { get; set; }
        public ICollection<Race> Races { get; set; }
    }

Именно в AppUser и нужно изменить тип на int

public class Race
    {

        [Key]
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string? Image { get; set; }
        public DateTime? StartTime { get; set; }
        public int? EntryFee { get; set; }
        public string? Website { get; set; }
        public string? Twitter { get; set; }
        public string? Facebook { get; set; }
        public string? Contact { get; set; }

        [ForeignKey("Address")]
        public int? AddressId { get; set; }
        public Address Address { get; set; }
        public RaceCategory RaceCategory { get; set; }

        [ForeignKey("AppUser")]
        public int? AppUserId { get; set; }
        public AppUser? AppUser { get; set; }

    }

public class Club
    {

        [Key]
        public int Id { get; set; }
        public string? Title { get; set; }
        public string? Description { get; set; }
        public string? Image { get; set; }

        [ForeignKey("Address")]
        public int? AddressId { get; set; }
        public Address? Address { get; set; }
        public ClubCategory ClubCategory { get; set; }

        [ForeignKey("AppUser")]
        public int? AppUserId { get; set; }
        public AppUser? AppUser { get; set; }

    }

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : IdentityDbContext<AppUser>
    {

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }

        public DbSet<Race> Races { get; set; }
        public DbSet<Club> Clubs { get; set; }
        public DbSet<Address> Addresses { get; set; }

        
    }
5
  • Не знаю на счёт postgresql, не в тему, в EntityFrameworkCore это делается проще metanit.com/sharp/efcore/3.6.php
    – xellan
    18 мая 2023 в 16:00
  • Если правильно понял что бы сделать в классе AppUser было public string Id { get; set; } в остальных классах должно быть public string? AppUserId { get; set; } 19 мая 2023 в 6:51
  • Я пробывал в AppUser сделать public string Id { get; set; } и в остальных классах public string? AppUserId { get; set; }, но в postgres колонка Id должна быть целочисленного типа (int, smallint и тд). Нужно именно чтобы в AppUser тип поля Id стал int, а проблема в том, что Identity делает Первичный ключ по умолчанию типа string и никак изменить тип не получается.
    – Grigory
    19 мая 2023 в 7:21
  • в Identity вот так public virtual TKey Id { get; set; } А ошибка ваша говорит что у вас несовместимые типы ключей в таблицах. 19 мая 2023 в 7:41
  • Странно, в сплывающем окне над полем Id высвечивается "AppUser.id скрывает наследуемый член Identity< string >.id." то есть изначально он как string подставлен, то что не соотвествие типов ключей в таблице я понимаю, вот поэтому и пытаюсь изменить главный на int, чтобы все были одного типа, но из-за проблемы описанной выше не могу.
    – Grigory
    19 мая 2023 в 8:15

1 ответ 1

0
ApplicationDbContext : IdentityDbContext<AppUser, int>

Если правильно понял о чем идет речь.

2
  • В таком случае выдаёт ошибку: "Не универсальный тип "IdentityDbContext" нельзя использовать с аргументами типа."
    – Grigory
    20 мая 2023 в 12:02
  • Попробуйте тогда вместо string использовать генерик аргумент
    – Tentrun
    20 мая 2023 в 14:41

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.