I'm building a project in MVC template using AspNet Core.
I've used Entity Framework and I've scaffolded an existing DB. Now, I want to add some Data Annotations to some class, but I don't wanna edit the class autogenerated by the scaffolding, so I've tried with the Metadata and the overriding of an existing method, the saveChanges
.
Users.cs autogenerated by Scaffolding
public partial class Users
{
public int UserId { get; set; }
...
// If I have [MaxLength(5, ErrorMessage = "Too short")] here, it works
public string Email { get; set; }
}
UsersMetadata.cs (also tried Users.Metadata.cs or else, nothing changed)
[ModelMetadataType(typeof(UsersModelMetaData))]
public partial class Users { }
public class UsersModelMetaData
{
[MaxLength(5, ErrorMessage = "Too short")]
public string Email { get; set; }
}
MyContext : DbContext Class
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();
}
So, even if this seems to be the correct solution (i've search all morning), it doesn't work: the problem seems to be that the Data Annotation inside UsersModelMetaData
aren't read, because if I put the Data Annotation directly in Users.cs
file, method saveChanges()
will throw an exception.
I did found this solution -> https://stackoverflow.com/a/30127682/6070423 <- but it's based on AspNet, and using AspNet Core I cannot use AssociatedMetadataTypeTypeDescriptionProvider
.
Any idea how I could resolve this?