Reputation: 67
I have in my database a table of Services and a table of BodyAreas. They are linked by a many to many relation. Here I'm trying to load Services from a CSV in which I have a also the related BodyAreas.
var record = reader.GetRecord<ServiceModel>();
service.Name = record.Service;
service.Code = record.ID;
service.Description = record.Description;
service.Price = decimal.Parse(record.Price_Uninsured);
service.Specialties = new[]
{
context.Specialties.FirstOrDefault(b => b.Name == record.Category),
};
service.ServiceType = serviceType;
service.BodyAreas = new List<BodyArea>();
string[] items = record.Body_Areas.Split(new char[] { ',' });
foreach (var item in items)
{
BodyArea bA = context.BodyAreas.Single(x => x.Name == item);
if (bA != null)
{
service.BodyAreas.Add(bA);
}
}
var entry = context.Entry(service);
if (entry.State == EntityState.Unchanged)
entry.CurrentValues.SetValues(service);
else
context.Services.Add(service);
But when I run the update-database command from the package manager console I get this error:
InnerException = {"Violation of PRIMARY KEY constraint 'PK_dbo.ServiceBodyAreas'. Cannot insert duplicate key in object 'dbo.ServiceBodyAreas'. The duplicate key value is (1, 17).\r\nThe statement has been terminated."}
Upvotes: 0
Views: 1527
Reputation: 3408
Make sure you are not trying to fill in duplicate values; try to avoid duplicates in the below line of code; you may use Distinct
to get unique values;
string[] items = record.Body_Areas.Split(new char[] { ',' });
Upvotes: 0