c# - 迭代 T4 脚手架中的 [ComplexType] 属性?

标签 c# asp.net entity-framework metadata t4scaffolding

我正在自定义 Entity Framework ASP.NET CRUD 模板,用于添加=>新脚手架项目...=>“使用 Entity Framework 的带 View 的 MVC 5 Controller ”。我还将 [ComplexType] 属性与用于实体属性的类一起使用(例如,[ComplexType] FullName 类用于我的 Customer 实体类中的 SpouseFullName 属性)。

public class Customer
{
    public string CustomerNumber { get; set; }
    public FullName SpouseFullName { get; set; } 
}

[ComplexType]
public class FullName
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }

    public FullName()
    {
        FirstName = "";
        MiddleName = "";
        LastName = "";
    }
}

我希望能够在搭建脚手架时迭代我的 [ComplexType] 中每个属性的属性元数据。例如:

<#
IEnumerable<PropertyMetadata> properties = ModelMetadata.Properties;
foreach (PropertyMetadata property in properties) 
{
    // Is this a [ComplexType]?
    if(property.IsComplexType)
    {
        // Iterate over metatdata here.
    }
}

理想情况下,我希望能够得到 IEnumerable<PropertyMetadata>我的 [ComplexType] 中包含的属性。想法?

最佳答案

想通了。我希望有更优雅的东西,但这行得通:

<#
    IEnumerable<PropertyMetadata> properties = ModelMetadata.Properties;
    foreach (PropertyMetadata property in properties) 
    {
        if(property.IsComplexType)
        {
            System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFile("C:\\myFullAssemblyPath\\bin\\Release\\myAssembly.dll");
            Type myType = myAssembly.GetType(property.TypeName);

            if(myType == null)
            {
#>
    <th>TODO:  Unable to render complex type (cannot load class from assembly). </th>
<#              
            }
            else
            {
                foreach(var currentComplexProperty in myType.GetProperties())
                {
                    string fullComplexName = property.PropertyName + "." + currentComplexProperty.Name;    
#>
            <th id="<#= fullComplexName #>">
                <#= fullComplexName #>
            </th>
<#        
                }
            }
        }
    }
#>

这使用反射加载复杂类型的程序集,不需要引用。一旦你有了它,你就可以获取类型并迭代属性。

关于c# - 迭代 T4 脚手架中的 [ComplexType] 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911190/

相关文章:

c# - 将linq查询结果存储在Model中

C# 版本的 WebForms 页面不工作,VB 版本是

c# - 如何从 Entity Framework 中的存储过程中获取数据作为数据集

c# - RADEditor 元素的 CSS 属性未被覆盖

javascript - c# 转换为 html 时停止“转换为”

c# - 如果我不再关心结果,是否还有结束委托(delegate)的方法?

c# - 如何用C#登录vbulletin论坛?

c# - 如何使 UpdatePanel 忽略单击其中的一个按钮?

entity-framework - Entity Framework 是否与 SQL Azure 兼容?

asp.net-mvc - 在 ASP.NET MVC 5 中使用 Entity Framework 中的存储过程从多个表中获取多条记录