Validating against a duplicate entry in ASP.NET 5 MVC 6

asp.net-core asp.net-core-mvc entity-framework-core

Question

Using asp.net 5, MVC 6, code first, entity Framework 7, beta 8.

I understand that some validation can be handled through annotations on properties, e.g. Data Type, min, max values and the jquery scripts, but I'm not sure how in code validation against a duplicate entry getting into the database, like preventing a duplicate e-mail reg on a form.

Is there any annotation that I can use for this on my model property or do I need to code something in my controller to handle this custom validation? Anyone got an example to share?

1
0
11/3/2015 12:38:12 AM

Popular Answer

EF7 does not have any magic to prevent duplicate values in a table. The only way to validate duplicates is to make a roundtrip to the database. The best way to do this is with a unique constraint. This may be expressed as a unique index. Any attempt to insert a duplicate entry should throw an exception.

That said, you can configure EF7 to recognize the unique index in your database in your OnConfiguring method. See Indexes : Configuring Your Model in the EF7 docs.

        modelBuilder.Entity<User>()
            .Index(b => b.Email)
            .Unique();
0
11/3/2015 5:11:07 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