Entity Framework/MVC3: temporarily disable validation

Alex Avrutin picture Alex Avrutin · Nov 11, 2011 · Viewed 14.3k times · Source

I am using EF Code First. I heavily use code annotations to specify how the data (model) should be validated. However, often I just need validation at UI layer and be able to suppress validation when I save certain data to the database in the code. However, once I specified validation rules, they are applied everywhere -- on the UI, on the database, on the data access layer.

Can I temporarily disable model validation at EF layer so I can save the data using SaveChanges() without getting validation exceptions?

Answer

Eranga picture Eranga · Nov 12, 2011

You just need to set Configuration.ValidateOnSaveEnabled = false in your context class before calling SaveChanges().

context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();