0
votes

I'm currently storing the enum type in Model A like so:

[Required]
public virtual RoleType RoleType { get; set; } = RoleTypeEnum.Normal;

RoleType.cs:

public enum RoleTypeEnum
{
    Normal,
    GlobalCommands,
    GlobalMacros,
    Staff
}

public class RoleType
{
    private RoleType(RoleTypeEnum @enum)
    {
        RoleTypeId = (int)@enum;
        Name = @enum.ToString();
        Description = @enum.GetEnumDescription();
    }

    protected RoleType() { } //For EF

    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int RoleTypeId { get; set; }

    [Required]
    public string Name { get; set; }
    public string Description { get; set; }

    public static implicit operator RoleType(RoleTypeEnum @enum) => new RoleType(@enum);
    public static implicit operator RoleTypeEnum(RoleType roleType) => (RoleTypeEnum)roleType.RoleTypeId;
}

In OnModelCreating:

builder.SeedEnumValues<RoleType, RoleTypeEnum>(e => e);
// ..
public static void SeedEnumValues<T, TEnum>(this ModelBuilder mb, Func<TEnum, T> converter) 
    where T : class where TEnum : Enum 
    =>
        Enum.GetValues(typeof(TEnum))
            .Cast<object>()
            .Select(value => converter((TEnum)value))
            .ToList()
            .ForEach(instance => mb.Entity<T>().HasData(instance));

However, upon adding a Model A to the database, like so:

public void AddGuildIfUnique(DiscordGuild dGuild)
{
    if (!GuildExists(dGuild, out Guild guild))
    {
        Console.WriteLine("Guild doesn't exist");
        guild = new Guild(dGuild);
        Database.Add(guild); //Exception here
    } 
    Console.WriteLine(guild.GuildName);
}

The following exception occurs on Database.Add(guild);:

The instance of entity type 'MyEnum' cannot be tracked because another instance with the key value '{MyEnumId: 0}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

1
Have you tried removing the default Enum value on Model A. - Rod Talingting
@RodTalingting Seems to have fixed it, but why? Feel free to explain in a standalone answer - Ali Bdeir

1 Answers

1
votes

Remove the default value of RoleType on your Model A (DiscordGuild?). This is because the RoleType in your Model A will populate the RoleTypeId on your RoleType class. And you can't have the same Key because they need to be unique.