Question

If I have two business objects, with a related field (foreign key CountryId), how do I display the CountryName in place of the CountryId when I display a list of the employee class?

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string FamilyName { get; set; }
    public int CountryId { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string CountryName { get; set; }
}
Was it helpful?

Solution

If you have a list of employees and a list of all countries, you could use LINQ to join them and create an anonymous object with the properties you need:

List<Employee> employees = // Get list of all employees
List<Country> countries = // Get list of all countries

var employeesWithCountryName = 
from e in employees
join c in countries on e.CountryID = c.Id
select new { 
  Id = e.Id, 
  FirstName = e.FirstName, 
  FamilyName = e.FamilyName,
  CountryId = e.CountryId, 
  CountryName = c.CountryName
}

OTHER TIPS

If you are using an ORM, then most of them allow you to navigate the relationship in order to get the countries name and any other properties of country.

In database terms it would require a join.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top