Home > Enterprise >  SQL Errors from OnSave EF Core
SQL Errors from OnSave EF Core

Time:10-21

I have a piece of code within EF Core which should insert 100 rows into the destination table.

On purpose I have added an error, there is a column in SQL which is of type Varchar(150). I have added more than that in a row - and yes I get the error but I do require the error for each row I insert into on the OnSave. Not just one error.

The SQL error is :

String or binary data would be truncated in table 'Area_of_Expertise_Type', column 'Name'.

Truncated value: 'gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg'.

So within code :

var AreaOfExpertiseType = new AreaOfExpertiseType
                {
                    AreaOfExpertiseTypeId = item.AreaofExpId,
                    Name = "gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",
                    Description = "Review Requirement for Description in CL"
                };

_clDBContext.AreaOfExpertiseType.Add(AreaOfExpertiseType);
               
try 
{
    _clDBContext.SaveChanges();
}
catch (DbUpdateException ex)
{
    // ErrList.Add(new ErrorList()
    //                 {
    //                     Error = ex.InnerException?.Message
    // });
    Console.WriteLine(ex.InnerException?.Message);
}

There is a for each above so I can add all the rows in. So as you can see I am trapping the OnSave.

Any ideas why I am only seeing one error? I want to get the id from the source database so I really need to see all the errors.

CodePudding user response:

To trigger an error per inserted row you will have to execute .SaveChanges() efter each insert, the insertion is processed as a transaction therefore it can only fail once.

It will be pretty inefficient to save for each row, generally i would advice against it.

  • Related