Muad'Dib
Muad'Dib

Reputation: 520

Entity Framework ViewModel

I have two tables in a database without any defined relationships.

    public class Person
    {
        public int PersonID { get; set; }
        public string Name { get; set; }
    }

    public class Car
    {
        public int CarID { get; set; }
        public string Model { get; set; }
        public int PersonID { get; set; }
    }

I created a PersonViewModel as below

        public class PersonViewModel
    {
        public int PersonID { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Car> Cars { get; set; }
    }

I would like to do some thing as below, but obvious it is incorrect. Any help would be greatly appreciated. Thank you

    public PersonViewModel GetPerson(int personID)
    {
        var query = from p in db.Car
                    join c in db.Car on p.PersonID equals c.PersonID
                    where p.PersonID == personID
                    select new PersonViewModel()
                    {
                        PersonID = p.PersonID,
                        Name = p.Name
                        Cars = new List<Car>()
                        {
                            CarID = c.CarID,
                            Model = c.Model,
                            PersonID = p.PersonID
                        }
                    };

        var person = query.FirstOrDefault();

        return person;
    }

Upvotes: 3

Views: 113

Answers (2)

Taher  Rahgooy
Taher Rahgooy

Reputation: 6696

You must join Person table with Car table, and then use this join group to generate the list of Cars :

    var query = from p in db.Person
                join c in db.Car on p.PersonID equals c.PersonID into personCars
                where p.PersonID == personID
                select new PersonViewModel()
                {
                    PersonID = p.PersonID,
                    Name = p.Name
                    Cars = personCars.ToList()
                };

    var person = query.FirstOrDefault();

Upvotes: 1

user2896170
user2896170

Reputation:

You are doing a join between the same table change the first table:

from p in db.Person

Upvotes: 0

Related Questions