Marcel Haldemann
Marcel Haldemann

Reputation: 791

C# Entity Framework (.Net Core) validation (server side) how to?

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");
                });
            }
        }
    }

Upvotes: 2

Views: 3016

Answers (2)

bricelam
bricelam

Reputation: 30425

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();
}

Upvotes: 2

Marcel Haldemann
Marcel Haldemann

Reputation: 791

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");
            }
        }

Upvotes: 0

Related Questions