无法将类型'System.Collections.Generic.List <string>'隐式转换为'System.Collections.Generic.List <Model> Mvc

时间:2019-12-23 14:15:19

标签: asp.net-mvc

我遇到问题无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.List 型号:

  public class UsersViewModels
{
    public AspNetUser aspNetUser { get; set; }
    public List<FuelerAppointment> appointmentslist { get; set; }
}

控制器:

 public ActionResult Index()
    {
        var model = new UsersViewModels();
        model.appointmentslist = db.AspNetUsers.Where(
        user => db.FuelerAppointments.Any(f => f.AspNetUserId == user.Id))
       .Select(user => user.UserName).ToList();

        return View(model);
    }

3 个答案:

答案 0 :(得分:2)

您的查询正在选择一个包含用户名的字符串列表。并且您不能将字符串列表转换为FuelerAppointment列表。您应该更改为:

 public ActionResult Index()
    {
        var model = new UsersViewModels();
        model.appointmentslist = db.AspNetUsers.Where(
        user => db.FuelerAppointments.Any(f => f.AspNetUserId == user.Id))
       .Select(user => user.FuelerAppointments).ToList();

        return View(model);
    }

答案 1 :(得分:1)

您正在选择一个用户名列表,因此您将以List<string>结尾,并且您的属性为List<FuelerAppointement>

答案 2 :(得分:0)

编译器不允许您执行此操作。您将列表声明为List<Object>,不能将其分配给String。如果您在username中正确地拥有FuelerAppointment

,则需要更改列表

我有两个相同的波纹管

 public class FuelerAppointment
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public int AspNetUserId { get; set; }
}

public class AspNetUser
{
    public string UserName { get; set; }
    public int Id { get; set; }
}

和viewModel:

public class UsersViewModels
{
    public List<FuelerAppointment> appointmentslist { get; set; }
}

我认为下面的代码可以帮助您

 [HttpGet]
    public UsersViewModels Get()
    {
        var model = new UsersViewModels
        {
            appointmentslist = (from user in _dbContext.AspNetUsers
                join fuelerAppointment in _dbContext.FuelerAppointments on user.Id equals fuelerAppointment.AspNetUserId
                select new FuelerAppointment { UserName = user.UserName }).ToList()
        };

        return model;
    }

结果:

enter image description here