Populate ViewModel with data returned from Entity Framework query

c# entity-framework-6

Question

I have the following view model

 public class VmPerson
 {
    public Person Person { get; set; }

    public PersonAddress PersonAddress { get; set; }

    public PersonEmploymentHistory PersonEmploymentHistory { get; set; }
 }

I make a call to a function and pass in a personId, I then try to populate the Person class as follows and pass back the ViewModel (there will be other queries in here to populate the address and employment history)

public VmPerson LoadPersonById(int personId)
{
        var vmPerson = new VmPerson();

        using (var context = new Context())
        {
            var r = (from p in context.Person
                join a in context.PersonAddress on p.PersonId equals a.PersonId
                join e in context.PersonEmployment on p.PersonId equals e.PersonId
                where p.PersonId == personId
                select new
                {
                    vmPerson.Person.PersonFirstName = p.PersonFirstName,
                    vmPerson.Person.PersonSurname = p.PersonSurname,
                    vmPerson.Person.PersonEmail= p.PersonEmail,
                    vmPerson.Person.Age = p.Age
                });
        }

        return vmPerson;
}

But I get an error on all the statements inside select new{} which is

Anonymous type projection initializer, should be simple name or member access expression

1
0
2/14/2019 9:47:45 AM

Accepted Answer

public VmPerson LoadPersonById(int personId)
    {
        using (var context = new Context())
        {

            var r = (from p in context.Person
                join a in context.PersonAddress on p.PersonId equals a.PersonId
                join e in context.PersonEmployment on p.PersonId equals e.PersonId
                where p.PersonId == personId
                select new VmPerson
                {
                    Person = p,
                    PersonAddress = a,
                    PersonEmploymentHistory = e
                }).FirstOrDefault();

            return r;
        }
    }
4
10/24/2014 10:42:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow