I am trying to remove an object and some other child objects using EF. Here's the method I am using:
public async Task<IHttpActionResult> Delete([FromBody]WordForm wordForm)
{
var olddObj = db.WordDefinitions
.Where(w => w.WordFormId == wordForm.WordFormId)
.AsNoTracking()
.ToList();
foreach (var wordDefinition in olddObj)
{
db.WordDefinitions.Attach(wordDefinition);
db.WordDefinitions.Remove(wordDefinition);
}
db.WordForms.Attach(wordForm);
db.WordForms.Remove(wordForm);
await db.SaveChangesAsync();
return Ok();
}
Can anyone explain to me why I might be getting this message:
Attaching an entity of type 'Entities.Models.Core.WordDefinition' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
Here's the object definition:
public class WordForm
{
public string WordFormId { get; set; } // WordFormId (Primary key) (length: 20)
public int WordFormIdentity { get; set; } // WordFormIdentity
// Reverse navigation
public virtual System.Collections.Generic.ICollection<WordDefinition> WordDefinitions { get; set; } // WordDefinition.FK_WordDefinitionWordForm
public WordForm()
{
WordDefinitions = new System.Collections.Generic.List<WordDefinition>();
}
}