Posts

Showing posts with the label validation

EF Core State Validation

Introduction How many times have you tried to save changes to your context only to get an exception about validation problems, like a required property being null ? I certainly have, and because of this, I came up with a solution to figure out what is happening. I will also provide some possible solutions for the problem of fully validating an entity using the Data Annotations API  (a post on general validation with Data Annotations here ). State Validation All the entities that are currently tracked by a DbContext have some state known to the context. This state includes: The entity's state ( State ) in regards to persistence ( Modified , Added , Deleted , Unchanged ) Each property's values ( Property ), both current ( Current ) and original ( Original ) The entity itself ( Entity ) Any navigation properties ( References , Navigations ) So, we can iterate through each tracked entry by means of the Entries , Entries<T> , or Entry methods: var entity = ...; var ent...

.NET 10 Validation

Note: this is an update to my original post . Introduction I wrote about  entity validation  in the past, the reason I'm coming back to it is that there are some changes in .NET 10, related to validation. Let's cover the original validation API and then explain what has changed. .NET Validation Validation is implemented in the System.ComponentModel.DataAnnotations namespace. I'll describe it first and then move to the small changes in .NET 10. .NET has featured a way to validate classes and their properties for a long time, the API is called  Data Annotations Validation , and it integrates nicely with ASP.NET Core MVC and other frameworks (not Entity Framework Core, as  I've talked recently , nor ASP.NET Core Minimal APIs ). It is essentially, but not just, based on a set of attributes, one interface, and a class that performs validations on a target class and its properties, from the validation attributes it contain. The base class for attribute validation is ca...