Mediator
Mediator

Reputation: 15378

how to ignore errors in SaveChange EF4

Please see to example1. If some of the data will be entered incorrectly, EF4 will not survive nor any record.

The question: whether as a force to ignore an error in one record and continue on.

example1:

foreach (var tag in split)
{
    context.NameToResourcer.AddObject(new NameToResourcer()
    {
        id_resource = resource.id,
        name = tag
    });
}
context.NameToResourcer.AddObject(new NameToResourcer()
{
    id_resource = resource.id,
    name = ExtractDomainNameFromURL(resource.url)
});
try
{
    context.SaveChanges();
}
catch (UpdateException ex)
{

}
catch (Exception ex)
{

    throw;
}

example2 alternative:

foreach (var tag in split)
{
    try
    {
        context.NameToResourcer.AddObject(new NameToResourcer()
        {
            id_resource = resource.id,
            name = tag
        });
        context.SaveChanges();
    }
    catch (UpdateException ex)
    {

    }
} 
try
{
    context.NameToResourcer.AddObject(new NameToResourcer()
    {
        id_resource = resource.id,
        name = ExtractDomainNameFromURL(resource.url)
    });
    context.SaveChanges();
}
catch (UpdateException ex)
{

}

Upvotes: 0

Views: 2494

Answers (2)

LoZo
LoZo

Reputation: 148

One possible solution is to disable validation on saving.But I don't recommend it.

db.Configuration.ValidateOnSaveEnabled = false;

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364399

Context behaves like unit of work. It means that when you modify data and store them with the single call to SaveChanges you are telling EF that you want atomic operation - either all changes are successfully saved or all changes are rolled back. EF use a transaction internally to support this behavior. If you don't want this behavior you cannot save all data with single call to SaveChanges. You must use separate call for each atomic set of data.

Upvotes: 3

Related Questions