c# - 在实体框架中返回“计算”字段
问题描述
我有这段代码。我的意图是创建字段,我可以将其作为 textValue 传递给 SelectList 对象。
这是我的两个实体:
public class Ski
{
public int ID { get; set; }
public int BrandID { get; set; }
public virtual Brand Brand { get; set; }
[NotMapped]
public string BrandName
{
get
{
return this.Brand.Name.ToString();
}
}
}
public enum BrandName
{
Blizzard, MCAD, ATOMIC
}
public class Brand
{
public int ID { get; set; }
public BrandName Name { get; set; }
}
和SelectList
初始化
ViewBag.SkiID = new SelectList(db.Skis, "ID", "BrandName");
但这样的解决方案似乎行不通。
那么这样的事情怎么可能实现呢?
错误说我有一个关联的 DataReader。
解决方案
创建此视图模型:
public class SkiViewModel
{
public string Text{ get; set; }
public int Value{ get; set; }
}
并更改您的代码:
var result = db.Skis.Select(x => new SkiViewModel()
{
Text = x.BrandName.Name ,
Value = ID
});
ViewBag.Skis = new SelectList(result, "Value", "Text");
并认为:
@Html.DropDownList("Value", new SelectListItem(ViewBag.Skis , "Value", "Text"))
推荐阅读
- homebrew - Brew 不会在 Mojave 上升级
- python - 记录 INFO 时如何让龙卷风打印出日期时间?
- angular-material2 - 获取角度 6、角度材料 2 中选定 mat-option mat-select 的文本/html 值
- python - 为什么不能修改 Class 的 Tkinter Button 配置?
- c# - 使用 FirefoxBinary.StartProfile() 在 headless 中运行 firefox
- sqlite - 在kivy中访问类之间的对象属性
- python - linux anaconda 环境不安装模块
- c++ - 对象数据成员的 C++ 连续内存访问
- google-apps-script - 为 Google Classroom 脚本添加范围会删除 SpreadsheetApp 的权限
- ios - 向 UIDynamicAnimator 添加超过 32 个 UIFieldBehavior 会导致 SIGABRT