vendredi 9 mars 2018

Add custom attribute to a class generated by entity framework

I am trying to use a custom attribute on a Entity class generated automatically by the Entity Framework.

The problem is how to add an property attribute on an existing field?

Here the point where i am right now:

//the custom attribute class
public class MyCustomAttribute : Attribute
{
    public String Key { get; set; }
}

//generated automatically
public partial class EntityClass
{
    public String Existent { get; set; }
    //property's
}

//set an metadata class for my entity
[MetadataType(typeof(EntityClassMetaData))]
public partial class EntityClass
{
    //if i add a new property to the Entity, it works. This attribute will be read
    [MyCustomAttribute(Key = "KeyOne" )]
    public int newProp { get; set; }
}

public class EntityClassMetaData
{
    //adding the custom attribute to the existing property
    [MyCustomAttribute(Key = "keyMeta") ]
    public String Existent { get; set; }    
}

Running this test:

    [TestMethod]
      public void test1()
    {
        foreach (var prop in typeof(EntityClass).GetProperties())
        {
            var att = prop.GetCustomAttribute<MyCustomAttribute>();

            if (att != null)
            {
                Console.WriteLine($"Found {att.Key}");
            }
        }                    
    }

will produce:

Found KeyOne

Or the Metadata class store the attribute in a different way or only works for data annotations.

I am stuck here, how can i set and read custom attributes of the generated class without having to edit the generated file?





Aucun commentaire:

Enregistrer un commentaire