简体   繁体   中英

Adding attributes to Entity Framework models nested classes properties

I've been searching for a way to add attributes to my entities classes properties and the only way I've found of reaching that was like in this example Adding custom property attributes in Entity Framework code

So I applied that to my project and it seemed like it should work well, but when I'm trying to reflect through the property attributes I'm getting null. I've checked my code for multiple times and just can't figure out why does it happens.

example of my code: in entity base model:

public partial class Trainer
{
    public Trainer()
    {
        this.Subjects = new HashSet<Subject>();
    }

    public int ID { get; set; }
    public int PersonalDataID { get; set; }

    public virtual PersonalData PersonalData { get; set; }
    public virtual ICollection<Subject> Subjects { get; set; }
}

in my partial class:

[MetadataType(typeof(Trainer.TrainerMetadata))]
public partial class Trainer
{
    internal class TrainerMetadata
    {
        [Search("PersonalData", true)]
        public virtual PersonalData PersonalData { get; set; }

        [Search("Subject", true)]
        public virtual ICollection<Subject> Subjects { get; set; }
    }
}

code I'm using for reflection:

foreach (PropertyInfo pI in typeof(Trainer).GetProperties())
{
  //sAttr always == null
  SearchAttribute sAttr = pI.GetCustomAttributes(typeof(SearchAttribute))
    .FirstOrDefault() as SearchAttribute; 
}

Any help will be appreciated.

Your SearchAttribute() are not applied to the Trainer class but to the TrainerMetadata class, so your foreach won't ever find them.

You need to do something like:

var metadata = typeof(Trainer).GetCustomAttributes(typeof(MetaDataAttribute))
  .FirstOrDefault();

if (metadata != null)
{
  var trainerMetadata = metadata.MetadataClassType;
  foreach (PropertyInfo pI in trainerMetadata.GetProperties())
  {
    var sAttr = pI.GetCustomAttributes(typeof(SearchAttribute))
      .FirstOrDefault() as SearchAttribute; 
  }
}

Although... I'm not sure why your partial that is not Generated doesn't just look like:

public partial class Trainer
{
  [Search("PersonalData", true)]
  public virtual PersonalData PersonalData { get; set; }

  [Search("Subject", true)]
  public virtual ICollection<Subject> Subjects { get; set; }
}

As Attributes of properties are merged when compiled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM