tags:

views:

34

answers:

2

When generating a strongly-typed Index view for my model I always get the following:

<%= Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %>

I am using a POCO class for use with our ORM. As I understand it when using LINQ to SQL the view code will know which field is the primary key.

Is there a way that I can an attribute to the property (or class) that will let the View Generator know that the ID property if the primary key?

+2  A: 

You use KeyAttribute, either directly or on a buddy class or through an associated metadata provider.

Craig Stuntz
Awesome. That seems to be a Framework 4 attribute. Is there anything for 3.5?
My Other Me
I don't know. It might be possible with an associated metadata provider. I haven't looked.
Craig Stuntz
+1  A: 

If I understood you correctly

[Column(IsPrimaryKey=true)]

should work.

Suggestion is based on function

public static List<string> GetEntityKeyProperties(Type type)
{
    List<string> keyProperties = new List<string>();

    PropertyInfo[] properties = type.GetProperties();

    foreach (PropertyInfo pi in properties)
    {
        System.Object[] attributes = pi.GetCustomAttributes(true);

        foreach (object attribute in attributes)
        {
            if (attribute is EdmScalarPropertyAttribute)
            {
                if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
                {
                    keyProperties.Add(pi.Name);
                }
            } else if(attribute is ColumnAttribute) {
                if ((attribute as ColumnAttribute).IsPrimaryKey == true)
                {
                    keyProperties.Add(pi.Name);
                }
            }
        }
    }

    return keyProperties;
}

placed in List.tt template in MVC 1.

LukLed
That did it. Thanks. (Works in MVC 2 as well)
My Other Me