2

I have a problem Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List Model :

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

Controller :

 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);
    }
1

3 Answers 3

2

Your query is selecting a list of the string contains UserNames. And you can not convert List of string to List of FuelerAppointment. You should change to:

 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);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You are selecting a list of UserNames, so you will end up with a List<string> and your property is a List<FuelerAppointement>.

Comments

0

Compiler doesn't let you to do this. You declared your list as List<Object> you can't assign it to String. you need to change list if you have username properly in FuelerAppointment

I have tow models same bellow.

 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; }
}

and viewModel:

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

I think bellow code can help you

 [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;
    }

Result:

enter image description here

3 Comments

I tried but I got error : System.NotSupportedException: 'The entity or complex type 'Startupfuels.Data.FuelerAppointment' cannot be constructed in a LINQ to Entities query.'
still the same :(
but i can do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.