Home > Software engineering >  Discard invalid entities before save in EF6
Discard invalid entities before save in EF6

Time:12-16

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 an DbEntityEntry<> object for the specified entity object.
  • error.Entry is already an DbEntityEntry<> 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();
  • Related