Rinkesh
Rinkesh

Reputation: 132

Create a table corresponding to enum Entity framework

I followed the below answer to insert enums into database;

How to create a table corresponding to enum in EF6 Code First?

But I am facing one strange issue. Every time I run the application, it additionally enters the last enum. For example, suppose i have three option for enum; Started, In Progress, Done. now on first run, it enters the 3 values as expected.

but on second run, there are four rows in database and Done is duplicated. Done is duplicated on each run.

PS: I have done some changes from above article.

  1. I used DatabaseGenerated(DatabaseGeneratedOption.Identity) instead of DatabaseGenerated(DatabaseGeneratedOption.None)

  2. My table is already in database

  3. I am using code-first approach and just wanted to re-factor code.

Am I doing anything wrong or is there any other solution to solve this?

Enum Class:

namespace ToDO.Data.Models
{
public class TaskStatus
{
    private TaskStatusTaskStatusEnum @enum)
    {
        Id = (int)@enum;
        Name = @enum.ToString();
        Description = @enum.GetEnumDescription();
    }

    protected TaskStatus() { } //For EF

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

    [Required, MaxLength(100)]
    public string Name { get; set; }

    [MaxLength(100)]
    public string Description { get; set; }

    public static implicit operator TaskStatusTaskStatusEnum @enum) => new TaskStatus(@enum);

    public static implicit operator TaskStatusEnumTaskStatus status) => (TaskStatusEnum)status.Id;
}
public enum TaskStatusEnum
{
    [Description("Started")]
    Started,
    [Description("In Progress")]
    InProgress,
    [Description("Done")]
    Done
}

}

EF Extenstion method to add values in database:

public static void SeedEnumValues<T, TEnum>(this IDbSet<T> dbSet, Func<TEnum, T> converter)
        where T : class => Enum.GetValues(typeof(TEnum))
                               .Cast<object>()
                               .Select(value => converter((TEnum)value))
                               .ToList()
                               .ForEach(instance =>  dbSet.AddOrUpdate(instance));

Result:

Database result

Thanks.

Upvotes: 0

Views: 1367

Answers (1)

Thom Kiesewetter
Thom Kiesewetter

Reputation: 7304

The AddOrUpdate does its compare with the primarykey. Enums starts from 0. This one is not in the database so it is added again. You can use AddOrUpdate(x=>x.Code.. etc

Upvotes: 1

Related Questions