相关业务对象中的外键

发布于 2024-08-01 19:24:02 字数 391 浏览 4 评论 0原文

如果我有两个具有相关字段(外键 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; }
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

屋顶上的小猫咪 2024-08-08 19:24:02

如果您有员工列表和所有国家/地区的列表,则可以使用 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
}

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
}
懷念過去 2024-08-08 19:24:02

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

用数据库术语来说,它需要联接。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文