将自定义属性添加到Entity Framework生成的类

时间:2018-03-09 17:41:44

标签: c# reflection custom-attributes

我正在尝试在Entity Framework自动生成的Entity类上使用自定义属性。

问题是如何在现有字段上添加属性?

这就是我现在的观点:

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

// Entity Framework class generated automatically
public partial class EntityClass
{  
    public String Existent { get; set; }
    //...
}

// set a 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; }    
}

运行此测试:

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

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

将产生:

  

找到KeyOne

或者Metadata类以不同的方式存储属性或仅适用于数据注释。

我被困在这里,如何在不必编辑生成的文件的情况下设置和读取生成的类的自定义属性?

2 个答案:

答案 0 :(得分:1)

我今天遇到了同样的问题。我认为EF魔术可以解决问题,并将属性映射到每个模型属性。事实证明确实如此,但仅适用于EF数据注释,我找不到提取自定义属性的答案解决方案,因此使用了此功能。希望对老兄有所帮助。

private object[] GetMetadataCustomAttributes(Type T, string propName)
    {
        if (Attribute.IsDefined(T, typeof(MetadataTypeAttribute)))
        {
            var metadataClassType = 
            (T.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault() as 
            MetadataTypeAttribute).MetadataClassType;
            var metaDataClassProperty = metadataClassType.GetProperty(propName);
            if (metaDataClassProperty != null)
            {
                return metaDataClassProperty.GetCustomAttributes(true);
            }
        }
        return null;
    }

答案 1 :(得分:0)

I believe if you want to set an attribute in the metadata class, you have to use this syntax:

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

You must not have { get; set; } on your pre-existing property - just the property with the correct name and datatype.