2

I started to use .net core (asp.net core) with the Entity Framework.

I plan to implement a webservice (using asp.net and GraphQL). now i wonder wheter it is possible use the use the RegularExpression Attribute for validation in the Entity Framework.

But it seems to be ignored.

All samples i found with such attributes was client and server side in C#.

Is this not supposed to work in the EF (serveside) like this ?

Is there an easy way to make this work without to write tons of code ?

PS: im using "Microsoft.EntityFrameworkCore" with PostgreSQL

Why is following Code not throwing an exception if the RegularExpression for Book.something is not meet (ps: it's also not firing if it's meet):

    ...
    using Microsoft.EntityFrameworkCore;
    using System.ComponentModel.DataAnnotations;

    namespace aspPlainEF
    {
        public class Startup
        {
            EFCoreDemoContext ef = new EFCoreDemoContext();

            ...

            public class Book
            {
                [Key]
                public int Id { get; set; }

                ...
                [Required]
                [RegularExpression(@"^hello$", ErrorMessage = "You can not have that")]
                public string something { get; set; }

            }

            public class EFCoreDemoContext : DbContext
            {
                public DbSet<Book> Books { get; set; }

                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
                    optionsBuilder.UseNpgsql(...);
                }
            }

            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                ...

                app.Run(async (context) =>
                {
                    Book book = new Book();
                    ...
                    book.something = "xxx";
                    ef.Add(book); ef.SaveChanges();
                    await context.Response.WriteAsync("hell1");
                });
            }
        }
    }
5
  • The RegularExpression attribute only applies to incomming data for ASP .NET, it's not an EF entity validation. You can write your own validator through reflection, create your own attribute, a class which searches for that attribute in classes and do the validation (it's a very rough description but I think the idea is clear). Commented May 5, 2017 at 16:00
  • @Gusman I seem to remember that at least in prior versions, EF would automatically validate entities with validation attributes applied? msdn.microsoft.com/en-us/library/gg193959.aspx That may have not made it into core yet though, if ever. Commented May 5, 2017 at 16:19
  • @AlexPaven Well, it seems you're right, I'm very rusty with EF, I need to recycle myself... (that's why I didn't added it as an answer :/ ). Commented May 5, 2017 at 16:51
  • i tested it on EF6 with .Net 4.6 there it works out of the box, so it appers to be an .note core issue. Commented May 5, 2017 at 19:03
  • Is still a need to manually implement the validation? Commented Apr 26, 2021 at 12:21

2 Answers 2

2

See my Validation in EF Core post for more details.

Here's the gist of it:

public override int SaveChanges()
{
    var entities = from e in ChangeTracker.Entries()
                   where e.State == EntityState.Added
                       || e.State == EntityState.Modified
                   select e.Entity;
    foreach (var entity in entities)
    {
        var validationContext = new ValidationContext(entity);
        Validator.ValidateObject(
            entity,
            validationContext,
            validateAllProperties: true);
    }

    return base.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

1 Comment

thx for the reply but even with this it doesn't work in .net core. I see that Validator.ValidateObject(entity, validationContext) is called correctly but it just passes the line and continues .... assuming bug in .net core 1.1 (as it works out of the box in .net 4.6 with ef6)
0

seems to be a problem in the current dotnetcore version Validation attributes don't work at all ??.

What however works is:

    public class Book : IValidatableObject
    {
    ...
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (something != "hello")
            {
                yield return new ValidationResult("Error message goes here");
            }
        }

Comments

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.