我有一个名为“schakeling”的类,使用EF生成,代表了数据库表“schakeling”。在数据库中,“id”是主键,“plc_id”是外键。
我有一个视图类
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以简洁为主)
@model PortalControl.ViewModels.SchakelingsListViewModel
<h2>Index</h2>
<table>
@foreach (var item in Model.List) {
@Html.TableRowFor(item)
}
</table>
我有一个通用的html帮助方法TableRowFor,因为我希望能够在使用EF生成的其他域实体上使用该方法。该方法生成简单的表格数据。
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()的东西会很好,但任何有效的解决方案都会受到赞赏。