4

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?

3
  • As the answer below states, yes you can do this. However, you really should be catching these errors before they become a problem. Validate the input before it gets anywhere near the context. Commented Jun 13, 2018 at 10:37
  • find the length of string and write comdition like if(len>255) throw err Commented Jun 13, 2018 at 10:38
  • @DavidG Yeah I've heard that you should validate before going to the context, but why is that? Because of performance? Commented Jun 14, 2018 at 11:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok great! StringLength attribute works! Is there any way to use data annotations attributes to check decimal length aswell?
Yes it exists => RangeAttribute.
Alright, but how would you define a range of 0 to 16 digits?
@skjold this may help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.