1

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.

Community
  • 1
  • 1
elch_yan
  • 61
  • 1
  • 10

1 Answers1

1

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • Because it's entity-framework specific. Entity-Framework knows that if you apply `MetaDataAttribute()` to use that for validation (And probably has code just as I wrote in it to validate fields). Unless I'm mistaken your custom `SearchAttribute()` has nothing to do with Entity-Framework so you have to actually write the code. – Erik Philips Mar 17 '14 at 22:34