I'm trying to implement a generic many-to-many Update method using EF6. Every time I try to update the navigation property, I get an exception:
"Violation of PRIMARY KEY constraint 'PK_dbo.Classes'. Cannot insert duplicate key in object 'dbo.Classes'. The duplicate key value is (698d5483-eb48-4d7e-84e7-a9f95a243d3d).\r\nThe statement has been terminated."
How can I fix it?
public void Update(T entity, params Expression<Func<T, IEnumerable>>[] navProps)
{
using (var context = new Context())
{
T foundEntity = context.Set<T>().Find(entity.Id);
var entry = context.Entry(foundEntity);
entry.CurrentValues.SetValues(entity);
foreach (var prop in navProps)
{
string memberName;
var member = prop.Body as MemberExpression;
if (member != null)
{
memberName = member.Member.Name;
}
else
{
throw new Exception();
}
var collection = entry.Collection(memberName);
collection.Load();
collection.CurrentValue = typeof(T).GetProperty(memberName).GetValue(entity);
}
context.SaveChanges();
}
}