The first time I add a migration my seeding works. However, if I run it again I get the exception
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Attributes' with unique index 'IX_AttributeName'. The duplicate key value is (State).
From my understanding, AddOrUpdate should not add if the entity already exists. Am I misunderstanding?
Attribute Entity
public class Attribute
{
public Attribute()
{
IsList = false;
}
public int AttributeId { get; set; }
[Required]
[StringLength(255)]
[Index("IX_AttributeName",1,IsUnique = true)]
public string AttributeName { get; set; }
public bool IsPHI { get; set; }
public bool IsList { get; set; }
public virtual ICollection<AttributeTerm> AttributeListTerms { get; set; }
}
Portion of Seeding class (updated after Gusman's advice)
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(GBARDbContext context)
{
var attributes = new[]
{
new Attribute {AttributeId = 2, AttributeName = "First Name"},
new Attribute {AttributeId = 3, AttributeName = "Last Name"},
new Attribute {AttributeId = 4, AttributeName = "Middle Name"},
new Attribute {AttributeId = 5, AttributeName = "Street"},
new Attribute {AttributeId = 1, AttributeName = "State", IsList = true},
};
context.Attributes.AddOrUpdate(a => a.AttributeId, attributes);
context.SaveChanges();