[英]Returning 'computed' field in Entity Framework
I have this piece of code. 我有这段代码。 My intention is to create field, which I can pass as textValue to SelectList object.
我的目的是创建字段,我可以将其作为textValue传递给SelectList对象。
Here are my two entities: 这是我的两个实体:
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; }
}
And SelectList
initialization 和
SelectList
初始化
ViewBag.SkiID = new SelectList(db.Skis, "ID", "BrandName");
But such a solution does not seem to work. 但是这样的解决方案似乎不起作用。
How can such a thing be implemented then? 那怎样才能实现呢?
Error says that I have an associated DataReader. 错误说我有一个关联的DataReader。
Create this view model: 创建此视图模型:
public class SkiViewModel
{
public string Text{ get; set; }
public int Value{ get; set; }
}
and change your code: 并更改您的代码:
var result = db.Skis.Select(x => new SkiViewModel()
{
Text = x.BrandName.Name ,
Value = ID
});
ViewBag.Skis = new SelectList(result, "Value", "Text");
and in view: 在视野中:
@Html.DropDownList("Value", new SelectListItem(ViewBag.Skis , "Value", "Text"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.