通过ViewBag将NotMapped属性传递给DropdownList

时间:2013-11-20 13:42:25

标签: c# asp.net asp.net-mvc razor

public class EmployeeDetail
{
    [Key]
    public int EmployeeId { get; set; }

    public string FirstName { get; set; }

    public string MiddleName { get; set; }

    public string LastName { get; set; }

    [NotMapped]
    public string FullName
    {
        get
        {
            return (this.FirstName + " " + this.MiddleName + " " + this.LastName).ToUpper();
        }
    }
}

创建操作方法

public ActionResult CreateEmploymentType()
{
    PopulateEmployeeIdDropDownList();
    return View();
}

填充方法

private void PopulateEmployeeIdDropDownList(object selectedEmployeeId = null) 
{

    var EmployeeIdQuery = from d in db.EmployeeDetails
                  orderby d.FullName
                  select d;

    ViewBag.EmployeeId = new SelectList(EmployeeIdQuery, "EmployeeId", "FullName", selectedEmployeeId);
}

查看下拉列表

EmployeeName: @Html.DropDownListFor(model => model.EmployeeId, (SelectList)ViewBag.EmployeeId)

问题:

当我运行应用程序时,它会显示错误消息

  

LINQ to Entities不支持指定的类型成员'FullName'。仅支持初始化程序,实体成员和实体导航属性。

2 个答案:

答案 0 :(得分:0)

通过将查询发送到列表来摆脱延迟执行:

ViewBag.EmployeeId = new SelectList(
    EmployeeIdQuery.ToList(), "EmployeeId", "FullName", selectedEmployeeId);

答案 1 :(得分:0)

我认为问题在于LINQ查询,因为FullName在数据库中不存在LINQ to Entities无法生成查询。所以手动设置

var EmployeeIdQuery = from d in db.EmployeeDetails
              orderby d.FirstName + " " + d.MiddleName + " " + d.LastName
              select d;

我还建议您代替查询传递Output并删除延迟执行。

ViewBag.EmployeeId = new SelectList(
    EmployeeIdQuery.ToList(), "EmployeeId", "FullName", selectedEmployeeId);