I used the accepted solution at this link for a similar problem to the OP. Validating entities before saving and removing from context
In Entity Framewok 6 I get System.InvalidOperationException: 'The entity type DbEntityEntry is not part of the model for the current context.'
How do I work around that? Is there something I have to include in my initial setup?
My code looks like this
Console.WriteLine("Removing Bad Records");
foreach (var error in context.GetValidationErrors())
{
context.Entry(error.Entry).State = EntityState.Detached;
}
Console.WriteLine("Saving Changes");
context.SaveChanges();
CodePudding user response:
context.Entry( Object )
returns anDbEntityEntry<>
object for the specified entity object.error.Entry
is already anDbEntityEntry<>
object. It is not an entity object.
So change your code to this (setting State
on your error.Entry
):
Console.WriteLine("Removing Bad Records");
foreach( var error in context.GetValidationErrors() )
{
error.Entry.State = EntityState.Detached;
}
Console.WriteLine("Saving Changes");
context.SaveChanges();
...or this (passing the actual entity object into dbContext.Entry(Object)
):
Console.WriteLine("Removing Bad Records");
foreach( var error in context.GetValidationErrors() )
{
var entity = error.Entry.Entity;
context.Entry( entity ).State = EntityState.Detached;
}
Console.WriteLine("Saving Changes");
context.SaveChanges();