Eitan K
Eitan K

Reputation: 837

Cannot insert duplicate key row in object

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();

Upvotes: 2

Views: 3929

Answers (2)

Eitan K
Eitan K

Reputation: 837

I fixed this by listening to Gusman and Alex S's advice of using the primary key to seed with. I had to delete all data and reset the identity counter first for the Attribute table and its depending AttributeTerm table

DBCC CHECKIDENT ('Attributes', RESEED, 0)
DBCC CHECKIDENT ('AttributeTerms', RESEED, 0)

Upvotes: 1

Francinaldo Portela
Francinaldo Portela

Reputation: 96

You have two columns that are unique right? The AttributeId and the AttributeName, so in the AddOrUpdate you should set this. Here's the solution:

context.Attributes.AddOrUpdate(a => new { a.AttributeId , a.AttributeName} , attributes);
context.SaveChanges();

Upvotes: 0

Related Questions