How to determine if a PropertyType is foreign key

血红的双手。 提交于 2019-12-01 18:14:44

You can get reference navigation properties from the Entity Framework conceptual model by this method:

IEnumerable<string> GetReferenceProperies<T>(DbContext context)
{
    var oc = ((IObjectContextAdapter)context).ObjectContext;
    var entityType = oc.MetadataWorkspace.GetItems(DataSpace.OSpace)
                       .OfType<EntityType>()
                       .FirstOrDefault (et => et.Name == typeof(T).Name);
    if (entityType != null)
    {
        foreach (NavigationProperty np in entityType.NavigationProperties
                .Where(p => p.ToEndMember.RelationshipMultiplicity
                                     == RelationshipMultiplicity.One
                         || p.ToEndMember.RelationshipMultiplicity
                                     == RelationshipMultiplicity.ZeroOrOne))
        {
            yield return np.Name;
        }
    }
}

It gets all navigation properties that have 0..1 at the end of the association, so that excludes collection navigation properties.

Now you can use the property names to get the matching PropertyInfos and get the value of the properties.

I got it working using your method, many thanks. For others, keep in mind this solution only works if you use a naming convention like mine(however, you can use the method of Gert as a guidance to pave the way for you're own solution):

  • Give a foreign key the exact same name as the the name of the db table it refers to
  • End the name with '_id'

Example:

You have a db table named user and want to create a new db table named bill. You want to refer a bill to an user using a FK, so in my situation I would name the FK user_id

Updated method TableRowFor:

public static MvcHtmlString TableRowFor<T>(this HtmlHelper helper, T obj)
{
    string controller = obj.GetType().BaseType.Name;
    string id = obj.GetType().GetProperty("id").GetValue(obj).ToString();

    StringBuilder sb = new StringBuilder("<tr>");
    sb.Append("<td>");
    sb.Append("<a href='" + controller + "/Edit/" + id + "'><img src='/Images/edit-icon.png' /></a>");
    sb.Append("<a href='" + controller + "/Details/" + id + "'><img src='/Images/details-icon.png' /></a>");
    sb.Append("<a href='" + controller + "/Delete/" + id + "'><img src='/Images/delete-icon.png' /></a>");
    sb.Append("</td>");

    List<string> referencePropertyList = GetReferenceProperies<T>(new NameOfDB()).ToList();
    foreach (var property in obj.GetType().GetProperties())
    {
        //If statement below filters out the two virtual properties(plc, verbruik) of the schakeling class(as said, generated with EF), somewhat ugly but it works, better suggestions are welcome..
        if ((!property.PropertyType.Name.ToLower().Contains("icollection")) && (property.PropertyType.CustomAttributes.Count() != 0))
        {
            sb.Append("<td>");
            //if property is foreign key
            if (referencePropertyList != null && property.Name.Length >= 3 && referencePropertyList.Contains(property.Name.Substring(0, property.Name.Length - 3)))
                sb.Append("<a href='" + property.Name.Substring(0, property.Name.Length - 3 ) + "/Details/" + property.GetValue(obj) + "'>" + property.GetValue(obj) + "</a>");
            else
                sb.Append(property.GetValue(obj));
            sb.Append("</td>");
        }
    }
    sb.Append("</tr>");
    return new MvcHtmlString(sb.ToString());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!