【问题标题】:Foreign Key in related Business Objects相关业务对象中的外键
【发布时间】:2009-08-14 10:07:24
【问题描述】:

如果我有两个具有相关字段(外键 CountryId)的业务对象,当我显示员工类列表时,如何显示 CountryName 来代替 CountryId?

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

【问题讨论】:

  • 您必须更加具体。 ASP.NET、WinForms、WPF、Silverlight 还是什么?你用什么组件来显示等等。

标签: .net business-objects


【解决方案1】:

如果您有一个员工列表和所有国家/地区的列表,您可以使用 LINQ 将它们加入并创建一个具有您需要的属性的匿名对象:

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
}

【讨论】:

  • 谢谢,看起来是实现这一目标的最简单方法。我打算在 Employee 类中创建 Country 类的实例,但 linq 选项看起来要容易得多!
【解决方案2】:

如果您使用的是 ORM,那么它们中的大多数都允许您浏览关系以获取国家/地区名称和国家/地区的任何其他属性。

在数据库方面,它需要一个连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多