如何获得自定义EF6 Designer属性的值

时间:2017-04-18 10:34:39

标签: entity-framework-6 t4

我已经成功扩展了EF6设计器,以便使用这篇文章在我的实体,关联和属性上允许一些自定义属性:

Extending Entity Framework 6 - adding custom properties to entities in designer

现在我需要在T4中生成代码时使用这些自定义属性,但我不知道如何访问该信息。有人能指出我正确的方向吗?

的问候, Jurjen。

1 个答案:

答案 0 :(得分:0)

我已经明白了。

例如,查看“foreach(varMap in typeMapper.GetItemsToGenerate(itemCollection))中的实体变量”,这是一个包含MetadataProperties的GlobalItem(https://msdn.microsoft.com/en-us/library/system.data.metadata.edm.globalitem(v=vs.110).aspx)。

使用简单的foreach

列出这些属性
foreach( var mp in entity.MetadataProperties)
{ 
    this.WriteLine("{0} = '{1}'", mp.Name, mp.Value);
}

产生一个列表

Name = 'Role'
NamespaceName = 'Model1'
Abstract = 'False'
...
http://saop.si:RecordTracked = '<a:RecordTracked xmlns:a="http://saop.si">true</a:RecordTracked>'
http://saop.si:DisplayMember = '<a:DisplayMember xmlns:a="http://saop.si">true</a:DisplayMember>'

如您所见,还列出了自定义属性(RecordTracked,DisplayName)。

我在公共类CodeStringGenerator中创建了2个函数来检索任何自定义属性。这样称呼:

CodeStringGenerator.GetCustomPropertyAsBoolean(entity, "RecordTracked");


private bool GetCustomPropertyAsBoolean(GlobalItem item, string propertyName)
{
    var _value = GetCustomProperty(item, propertyName);
    if (string.IsNullOrEmpty(_value ))
    { return false; }

    return _value.Equals("true", StringComparison.CurrentCultureIgnoreCase);        
}

private string GetCustomProperty(GlobalItem item, string propertyName)
{
    var _found = item.MetadataProperties.FirstOrDefault(p => p.Name.StartsWith("http://") && 
                                                             p.Name.EndsWith(propertyName, StringComparison.CurrentCultureIgnoreCase ));
    if (_found == null)
    { return string.Empty; }

    var _value = _found.Value as System.Xml.Linq.XElement;
    if (_value == null)
    { return string.Empty; }

    return _value.Value;
}
相关问题