1

I am new to Linq. I have to use Linq to Sql to project data from sql server to a complex object. The complex object is the Employee class which has another class, EmployeeDetail, as a property. I am able to populate the Employee class but unable to populate the EmployeeDetail. I have enclosed my code below. Obviously, I have to instantiate EmployeeDetail within the select new Employee block and attach it. Unfortunately, I don't know how to do it.

public class Employee
{
    public String Email { get; set; }        
    public String EmployeeId { get; set; }   
    public EmployeeDetail employeeDetail { get; set; }    
}

public class EmployeeDetail
{
    public String PhoneNumber { get; set; }
    public String Address { get; set; }
}

public class Data
{
    public List<Employee> GetEmployee()
    {
        EmployeeDataContext dbDontext = new EmployeeDataContext ();

        var employees = from i in dbDontext.Employee
                    join m in dbDontext.Employee on i.Employee_Id equals 
                    m.Emplyee_Detail_Id
                    select new Employee
                    {
                        Email = i.email,
                        EmployeeId = i.employee_Id.ToString(),
                        //how to get data for the EmployeeDetail property 
                        //with PhoneNumber  and Address values populated?
                    };
        var employeeList = employees.ToList();
        return employeeList;
    }
}
0

1 Answer 1

1

It's not really a LINQ question, more of an object initializer question. When you are initializing an object, you can set its properties:

new Employee
{
    Email = i.email,
    EmployeeId = i.employee_Id.ToString() 
}

The same syntax is true of its object type properties:

new Employee
{
    Email = i.email,
    EmployeeId = i.employee_Id.ToString(),
    employeeDetail = new EmployeeDetail
    {
        PhoneNumber = ...,
        Address = ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.