2

I am customizing the Entity Framework ASP.NET CRUD templates used for Add=>New Scaffolded Item...=>" MVC 5 Controller with views, using Entity Framework". I am also using the [ComplexType] attribute with classes that are used for entity properties (for example, a [ComplexType] FullName class is used for a SpouseFullName property in my Customer entity class).

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 = "";
    }
}

I would like to be able to iterate over the property metadata for each property in my [ComplexType] when scaffolding. For example:

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

Ideally, I would like to be able to get an IEnumerable<PropertyMetadata> of properties contained in my [ComplexType]. Ideas?

Richard Edwards
  • 103
  • 1
  • 10

1 Answers1

1

Figured it out. I was hoping for something more elegant, but this works:

<#
    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>
<#        
                }
            }
        }
    }
#>

This loads the assembly of the complex type using reflection and does not require a reference. Once you have that, you can get the type and iterate over the properties.

Community
  • 1
  • 1
Richard Edwards
  • 103
  • 1
  • 10