首页 > 解决方案 > 在实体框架中返回“计算”字段

问题描述

我有这段代码。我的意图是创建字段,我可以将其作为 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。

标签: c#asp.netentity-framework

解决方案


创建此视图模型:

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"))

推荐阅读