如何确定 PropertyType 是否为外键 [英] How to determine if a PropertyType is foreign key

查看:26
本文介绍了如何确定 PropertyType 是否为外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类schakeling",由 EF 生成,代表数据库表schakeling".在数据库中,'id' 是主键,'plc_id' 是外键.

I have the following class 'schakeling', generated with EF, representing a database table 'schakeling'. In the database 'id' is the primary key and 'plc_id' is a foreign key.

public partial class schakeling
{
    public schakeling()
    {
        this.verbruik = new HashSet<verbruik>();
    }

    public int id { get; set; }
    public int plc_id { get; set; }
    public string var_output { get; set; }
    public string omschrijving { get; set; }
    public int vermogen { get; set; }
    public Nullable<bool> status { get; set; }
    public Nullable<byte> hourOn { get; set; }
    public Nullable<byte> minuteOn { get; set; }
    public Nullable<byte> hourOff { get; set; }
    public Nullable<byte> minuteOff { get; set; }

    public virtual plc plc { get; set; }
    public virtual ICollection<verbruik> verbruik { get; set; }
}

我有一个视图类

public class SchakelingsListViewModel
{
    public IEnumerable<schakeling> List { get; set; }
    public PagingInfo PagingInfo { get; set; }//Not relevant for this question
    //And some more properties...also not relevant
}

我有以下视图(为简洁起见,省略了一些 HTML)

I have the following view (omitted some HTML for brevity)

@model PortalControl.ViewModels.SchakelingsListViewModel
<h2>Index</h2>
<table>
@foreach (var item in Model.List) {
    @Html.TableRowFor(item)
}
</table>

我有一个通用的 html 辅助方法 TableRowFor,因为我希望能够在使用 EF 生成的其他域实体上使用该方法.该方法生成简单的表数据.

I have a generic html helper method TableRowFor because I want to be able to use the method on other domain entities generated with EF. The method generates simple table data.

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>");

    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
                //sb.Append("<a href='" + correctControllerNameHere + "/Details/" + property.GetValue(obj) + "'><img src='/Images/details-icon.png' /></a>");
            //else
                //sb.Append(property.GetValue(obj));
            sb.Append("</td>");
        }
    }
    sb.Append("</tr>");
    return new MvcHtmlString(sb.ToString());
}

我的问题是,如果属性是外键,我想创建一个链接.

我在互联网上搜索过,但我不是 PropertyInfo、MetaDataClassType 和其他类似类的专家.像 property.isForeign() 这样的东西会很可爱,但任何有效的东西都会受到赞赏.

I have searched the internet but I am no expert in PropertyInfo, MetaDataClassType and other similar classes. Something like property.isForeign() would be lovely but anything that works will be appreciated.

推荐答案

可以通过这个方法从Entity Framework概念模型中获取参考导航属性:

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

它获取所有在关联末尾具有 0..1 的导航属性,因此不包括集合导航属性.

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

现在您可以使用属性名称来获取匹配的 PropertyInfo 并获取属性的值.

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

这篇关于如何确定 PropertyType 是否为外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆