foreign-keys - 在外键关系上显示名称属性
问题描述
我有一个外键选择列表(如父级)。目前,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 -->
你有一个想法来做对吗?
感谢提前
解决方案
查看脚手架 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();
// ...
}
推荐阅读
- javascript - 挣扎于页脚和模式
- vba - 如何将用户表单列表框中的选择填充到项目符号 MS-Word-VBA 中?
- postgresql - 在 PostgreSQL 中解析文本数据
- google-pay - 在谷歌支付(谷歌钱包)中存储二维码
- python - 如何将 Django env 文件夹添加到 .gitignore?
- javascript - 使用 Express Backend 动态更改 React Js 应用程序的元标记
- python - 检查与 AST 参数规范的兼容性
- android - 使用材料设计为 androidx.legacy:legacy-support-v4:1.0.0 更改 androidx.appcompat.widget.SearchView(操作栏中的搜索图标)
- python - 类型错误:+ 不支持的操作数类型:“datetime.datetime”和“datetime.time”
- r - 如何正确地将边际密度图添加到 ggplot 对象?