I have followed the accepted answer on this question, and all works perfectly fine... I get my table generated with my Enum values from the overriden Seed function in my initializer. However, when I then add further code into the seed function to populate another table making use of the Enum, I am finding it is trying to re-insert (the used enum) into the new enum-based table causing primary key validation errors. Here is the enum I am using:
public enum ComponentTypeEnum
{
template,
section,
header,
footer,
body,
label,
text,
image,
TOC,
Table,
TableColumn,
TableRow,
TableCell,
List
};
and I have a corresponding class called ComponentType:
public class ComponentType
{
private ComponentType(ComponentTypeEnum @enum)
{
Id = (int)@enum;
Name = @enum.ToString();
}
protected ComponentType()
{
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
public static implicit operator ComponentType(ComponentTypeEnum @enum) => new ComponentType(@enum);
public static implicit operator ComponentTypeEnum(ComponentType faculty) => (ComponentTypeEnum)faculty.Id;
}
In my Initializer I have the following:
protected override void Seed(DocumentPDFDbContext context)
{
context.ComponentType.SeedEnumValues<ComponentType, ComponentTypeEnum>(@enum => @enum);
context.SaveChanges();
var testItems = new List<ItemData>
{
new ItemData{Id = 1, ParentId = null, ComponentType = ComponentTypeEnum.template, Content = null, SortOrder = 1,},
new ItemData{Id = 2, ParentId = 1, ComponentType = ComponentTypeEnum.section, Content = null, SortOrder = 1,},
};
testItems.ForEach(t => context.ItemData.Add(t));
context.SaveChanges();
}
Before I added in the testItem code it was working fine and generating my lookup table fromt he Enum fine, with the above testItems code added it seems to be trying to re-insert whichever ComponentTypeEnum is being included in the data.
Im hoping this is just a simple EF thing that I am just unaware of.