无法将实体作为List添加到ViewModel?

时间:2016-05-11 23:09:13

标签: c# entity-framework entity-framework-6

目前我已经创建了一个ViewModel,我最初只是将“Status”列为字符串,但现在我决定将它变成DropDownList。我将这些CallStatus作为实体对象。所以,我想我可以创建一个类型为“CallStatus”的列表,然后当我创建我的ViewModel时,只需调用db.CallStatus.ToList()来填充它。然后我会使用该列表来创建我的DropDownList。但是,我收到一条错误,说“无法将类型'System.Collections.Generic.List'隐式转换为CPPCallStatus.Models.CallStatus”

这是我的VM。我在底部添加了CallStautsTypes,这就是我想要填充的内容。

public class CustomerCallVM
{
    public int Id { get; set; }

    [DisplayName("Customer Name")]
    public string CustomerName { get; set; }

    public string Subject { get; set; }

    public string Comment { get; set; }

    [DisplayName("Call Date")]
    public DateTime? CallDate { get; set; }

    public int? Status { get; set; }

    [DisplayName("Status")]
    public string StatusName { get; set; }

    public int? AssignedTo { get; set; }

    [DisplayName("Assigned To")]
    public string AssignedToName { get; set; }

    [DisplayName("Create Date")]
    public DateTime? CreateDate { get; set; }


    public CallStatus CallStatusTypes { get; set; }
}

这是我填充虚拟机的Repo。我知道我需要删除Lambda中的.include,但我认为这不是问题。

public CustomerCallVM SelectById(int? id)
{
    using (DataContext db = new DataContext())
    {
        db.Configuration.AutoDetectChangesEnabled = false;      

        CustomerCallVM customerCall = new CustomerCallVM();

        var call = db.CustomerCalls.Include(s => s.CallStatus).Where(c => c.Id == id).FirstOrDefault();

        if (call != null)
        {
            customerCall.Id = call.Id;
            customerCall.CustomerName = call.CustomerName;
            customerCall.Subject = call.Subject;
            customerCall.Comment = call.Comment;
            customerCall.CallDate = call.CallDate;
            customerCall.Status = call.Status;
            customerCall.AssignedTo = call.AssignedTo;

            customerCall.StatusName = call.CallStatus.StatusName;

            customerCall.CallStatusTypes = db.CallStatus.ToList();
        }

    return customerCall;
}

1 个答案:

答案 0 :(得分:4)

更改此行

text/plain

public CallStatus CallStatusTypes { get; set; }

正如消息所示,您正在尝试将public IEnumerable<CallStatus> CallStatusTypes { get; set; } 转换为List<CallStatus>CallStatus