How to add Data Validation in EF Core with Database First approach?

c# ef-database-first entity-framework entity-framework-core validation

Question

I am implementing a MVC-Webapplication with ASP.NET Core (RC2) and as ORM Entity Framework Core. Since I already got a database design, I have to create the entity models by the Scaffold-DBContext command.

This works fine. Now, I want to add some annotations to the generated entities in order to add validations. For example MaximumLength:

public class Blog
{
    public int BlogId { get; set; }
    [MaxLength(500)]
    public string Url { get; set; }
}

If there are some database changes, I have to use the scaffold command again. But this results to the loss of some additional annotations. How can I update the entity models without loosing them? According to asp.net page or from this topic, It seems to be possible with EF6. Is there a similar way to achieve this with EF7/Core?

1
2
5/23/2017 12:01:02 PM

Popular Answer

Yes,you can.You have to use Fluent API instead of Data Annotations.

Here is your example using Fluent API

public  partial class MyContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>()
                .Property(b => b.Url)
                .HasMaxLength(500);
        }
    }

Reference : EF core Doc

OP's feedback

But the Database context class will be also generated. This means, If I use the command again, it will replace the old database context.

My suggestion :

You can use partial class here.keep your custom implementation on that file.Those pieces of custom code won't get overwritten when you re-generate the code.

OP's feedback :

I could solve it with partial classes BUT after generating the entities, you have to go through all entities and delete all duplicated properties. Still not quite that what I am looking for, because you still have to modify the entities.

My suggestion :

You don't need to delete any duplicate mappings. B'cos EF gives precedence to the Fluent API.It doesn't matter what ever the mapping has done by the code regeneration automatically. You can overridden those using Fluent API.That is the power of Fluent API.You can also use DataAnnotation and Fluent API at the same time. But code-First gives precedence to Fluent API > data annotations > default conventions.

1
9/7/2016 11:49:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow