views:

57

answers:

2

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

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
}
Eric Petroelje
Thanks, looks like the simplest way to achieve this. I was going to create an instance of the Country class within the Employee Class, but the linq option looks much easier!
ob
A: 

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.

Fluxtah