我尝试在脚手架上下文中获取.Net核心中的相关实体。
我正在用MVC构建一个正在搭建的细节页面。我需要财产和导航。显示了所有相关属性,但是,只有non-ICollection导航属性是从.Navigations显示的。
正在加载的对象是Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ModelMetaData。
foreach (var property in Model.ModelMetadata.Properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
<dt>
@@Html.DisplayNameFor(model => model.@GetValueExpression(property))
</dt>
<dd>
@@Html.DisplayFor(model => model.@GetValueExpression(property))
</dd>
}
}
foreach (var navigation in Model.ModelMetadata.Navigations)
{
<dt>
@@Html.DisplayNameFor(model => model.@GetValueExpression(navigation))
</dt>
<dd>
<a asp-area="" @GetNavigationLinkExpression(navigation)>@@Html.DisplayFor(model => model.@GetValueExpression(navigation).@navigation.DisplayPropertyName)</a>
</dd>
}我的模特就是这样..。ModelMetaData只能通过第二个导航并跳过第一个。我在哪里可以访问第一个属性,以便我可以模板它?
public virtual ICollection<SomeModel> CollectionNavigationProperty1 { get; set; }
public virtual AnotherSomeModel NavigationProperty1 { get; set; }发布于 2018-04-24 14:56:50
嗯,经过几个小时的努力,我终于找到了一个解决方案,这个解决方案远没有我想要的那样有活力。我只是不知道如何获得实体模型的Type对象。
可以获得ICollection对象的列表,如下所示:
var icollections = new List<string>();
foreach (PropertyInfo property in
typeof(YourProjectName.ContextObject).Assembly
.GetType("YourProjectName.Entities." + Model.ModelTypeName)
.GetProperties())
{
if (property.PropertyType.IsGenericType
&& property.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
icollections.Add(property.Name);
}
}将“YourProjectName.ContextObject”替换为DbContext对象的完整命名空间和类名。替换“YourProjectName.Entities.”具有实体所在位置的完整命名空间。
只有当您的实体/模型保存在同一个命名空间中时,这才能正常工作。
希望有人能提供一个更好的解决方案,但这将是我现在使用的。
https://stackoverflow.com/questions/44855356
复制相似问题