Hello! In the console application on c #, using the Entity Framework, you need to make control of the recorded data. The Entity Framework does this on its own by executing the SaveChanges (SaveChangesAsync) method. But at the same time the diagnosis of the most common form. Type: An error occurred while updating the records. I would like to conduct a more detailed diagnosis (for example, validation tools in ASP.NET MVC). Are there such tools in the Entity Framework (other packages), or such diagnostics should be done independently?

Thanks in advance Vladimir

    1 answer 1

    In this case, your choice = System.ComponentModel.DataAnnotations

    Roughly speaking, it is a set of predefined attributes that can describe the constraints for each property in a class that describes a data model. There is a set of predefined constraints (ex. RequiredAttribute, MaxLengthAttribute, EmailAttribute, ReqularExpressionAttribute ...). In addition, it is possible to create your own custom attributes, inheriting from the basic interface. You can also add your own validation error message to any attribute.

    public class CreditCardStandartInfo { [Required] [RegularExpression("^[0-9]{16}$", ErrorMessage = "incorrect format")] public string CardNumber { get; set; } [Required] [MinLength(6)] public string CardholderName { get; set; } [Required] [RegularExpression("^[0-9]{3}$", ErrorMessage = "incorrect format")] public string CVVCode { get; set; } [Required] public virtual int ExpireMonth { get; set; } [Required] public virtual int ExpireYear { get; set; } } 

    If you use the EF CodeFirst, you can attach attributes directly to the data model. And EF automatically validates them during validation.

    If you have ModelFirst (there is no direct access to entity classes), then I suggest adding a layer of DTO objects and imposing attributes on them. And carry out the verification yourself. For this I propose to use the following code:

     public static class DataAnnotationsValidator { public static bool TryValidate(object instance, out ICollection<ValidationResult> results) { var context = new ValidationContext(instance, serviceProvider: null, items: null); results = new List<ValidationResult>(); return Validator.TryValidateObject( instance, context, results, validateAllProperties: true ); } } 

    If errors are found, you will receive a list of them that you provide to the client. If validation succeeds, you copy data from your DTO objects to the EF entity and perform the necessary operations from the database.

    • Thanks for the detailed and thorough answer. I will dig in this direction. - Vladimir Madorin
    • @ VladimirMadorin then it’s worth to mark my answer as correct. - nikita