Reputation: 51
You will get a DbUpdateException
if you try to save a string with length of 500 to a column in Sql Server which is a nvarchar(255).
Is there any way to check for this error before calling SaveChanges()
? Maybe when adding the entity to context?
Upvotes: 4
Views: 972
Reputation: 23190
Is there any way to check for this error before calling SaveChanges? Maybe when adding the entity to context?
Yes. It is possible by calling this method GetValidationErrors()
on your DbContext
like below but you will get the validation errors result only if you make use of data annoations attributes on your entity classes
var validationResults = dbContext.GetValidationErrors();
validationResults
will contain a collection of DbEntityValidationResult
so if empty then your tracked entities are valid. Then calling SaveChanges
just after will not throw exception about data validation but you can still get some others exceptions which can be checked only on server side e.g. concurrency exception, unique or reference constraint exception, etc.
Upvotes: 2