Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core MetaDataType Attribute not working

I'm using the MetaDataType Attribute on my domain model class. It it supposed to move the attribute information from the referenced class into the class that the MetadataType attribute has been set. But it doesn't do as advertised. What is causing the issue here?

[MetadataType(typeof(ComponentModelMetaData))] public partial class Component {     public int Id { get; set; }     public string Name { get; set; }     public ICollection<Repo> Repos { get; set; }     public string Description { get; set; }    }   public class ComponentModelMetaData {     [Required(ErrorMessage = "Name is required.")]     [StringLength(30, MinimumLength = 3, ErrorMessage = "Name length should be more than 3 symbols.")]     public string Name { get; set; }     public ICollection<Repo> Repos { get; set; }     [Required(ErrorMessage = "Description is required.")]     public string Description { get; set; }         } 
like image 953
Meta Avatar asked Jan 03 '16 13:01

Meta


2 Answers

ASP.NET Core uses

Microsoft.AspNetCore.Mvc **ModelMetadataType**  

instead of

System.ComponentModel.DataAnnotations.**MetadataType**  

source

Try changing your attribute to [ModelMetadataType(typeof(ComponentModelMetaData))]

like image 155
Guilherme Duarte Avatar answered Sep 16 '22 14:09

Guilherme Duarte


Entity class:

namespace CoreProject.Persistence.EFCore {     public partial class User     {         public User()         {             Reader = new HashSet<Reader>();             Writer = new HashSet<Writer>();         }          public int UserId { get; set; }         public string Email { get; set; }         public string Password { get; set; }         public string PasswordHashKey { get; set; }         public byte Role { get; set; }         public string FirstName { get; set; }         public string LastName { get; set; }         public DateTime CreatedUtc { get; set; }         public DateTime LastUpdateUtc { get; set; }         public byte Status { get; set; }         public bool Deleted { get; set; }         public DateTime? ActivatedUtc { get; set; }         public bool Test { get; set; }          public virtual ICollection<Reader> Reader { get; set; }         public virtual ICollection<Writer> Writer { get; set; }     } } 

Metadata (Both have to use the same namespace):

namespace CoreProject.Persistence.EFCore {     [ModelMetadataType(typeof(IUserMetadata))]     public partial class User : IUserMetadata     {         public string FullName => FirstName + " " + LastName;     }      public interface IUserMetadata     {         [JsonProperty(PropertyName = "Id")]         int UserId { get; set; }          [JsonIgnore]         string Password { get; set; }         [JsonIgnore]         string PasswordHashKey { get; set; }         [JsonIgnore]         byte Role { get; set; }     } } 
like image 33
Javier Contreras Avatar answered Sep 17 '22 14:09

Javier Contreras