简体   繁体   中英

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)
{

}

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.

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

db.Configuration.ValidateOnSaveEnabled = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM