首页 > 解决方案 > 在外键关系上显示名称属性

问题描述

我有一个外键选择列表(如父级)。目前,ID 绑定了值和项目名称。我想为我的 Name 属性更改它:

这是我的模型:

public class Genus
    {
        public int GenusID { get; set; }
        public EnumCategory Category { get; set; }
        public string Name { get; set; }

        public List<Species> Species { get; set; }
    }
public class Species
    {
        public int SpeciesID { get; set; }

        public int GenusID { get; set; }
        public virtual Genus Genus { get; set; }

        public string Name { get; set; }
    }

在我的创建和编辑物种页面上,我有以下代码:

<select asp-for="Species.GenusID" class ="form-control" asp-items="ViewBag.GenusID"></select>

我们添加 Razor Page Scaffold 时默认生成此代码。好吧,结果在第 1 行,而我想要的结果在第 2 行:

<option selected="selected" value="1">1</option>
<option selected="selected" value="1">NameProperty</option> <!-- Species.Genus.Name -->

你有一个想法来做对吗?

感谢提前

标签: foreign-keysentity-framework-corerazor-pages

解决方案


查看脚手架 repo ( https://github.com/aspnet/Scaffolding ) 中 NavigationMetadata 类的代码,我发现了以下描述行为的注释代码。

// The default for the display property is the primary key of the navigation. 
DisplayPropertyName = PrimaryKeyNames[0];

// If there is a non nullable string property in the navigation's target type, we use that instead. 
var displayPropertyCandidate = navigation
    .GetTargetType()
    .GetProperties()
    .FirstOrDefault(p => !p.IsNullable && p.ClrType == typeof(string));

if (displayPropertyCandidate != null)
{
    DisplayPropertyName = displayPropertyCandidate.Name;
}

因此,如果您希望默认显示 Name 属性而不是 ID,请确保它是模型中的第一个字符串属性(您的已经是),然后确保它不可为空。

protected override void OnModelCreating(ModelBuilder builder)
{
    // ...
    builder.Entity<Genus>().Property(l => l.Name).IsRequired();
    // ...
}

推荐阅读