简体   繁体   English

如何从外键获取值以使用关联值填充列表?

[英]How do I get a value from a foreign key to populate a list with an associated value?

I have the following list in my ViewModel:我的 ViewModel 中有以下列表:

public List<Objective> Objectives { get; set; }

I also have the following repository method:我还有以下存储库方法:

public async Task<List<Objective>> GetAll()
{
    return await _context.Objective.ToListAsync();
}

Finally I have the following method in a service which returns a ViewModel:最后,我在返回 ViewModel 的服务中有以下方法:

public async Task<ObjectivesViewModel> GetViewModel()
{
    var viewModel = new ObjectivesViewModel()
    {
        Objectives = await _objectivesRepository.GetAll()
    };

    return viewModel;
}

All of this works as expected.所有这些都按预期工作。

My Objective Model looks like this:我的目标模型如下所示:

public string ReferenceCode { get; set; }
public int TeamId { get; set; }
public string Description { get; set; )

With the TeamId Model looking like this: TeamId 模型如下所示:

public int TeamId { get; set; }
public string TeamName { get; set; }

As it stands, the repository returns all, as it should, however what I'd like to do is to add the TeamName associated with the TeamId.就目前而言,存储库应该返回所有内容,但是我想做的是添加与 TeamId 关联的 TeamName。 How would I accomplish or approach this?我将如何完成或解决这个问题?

Make TeamId foreign key, and access team navigation property Objective model:制作 TeamId 外键,并访问团队导航属性目标模型:

public string ReferenceCode { get; set; }
public int TeamId { get; set; }
[ForeignKey("TeamId ")]
public Team Team { set; get; }
public string Description { get; set; )

now you can access teamId or teamName现在您可以访问 teamId 或 teamName

Objective obj = _context.Objective.FirstOrDefault();
obj.Team.TeamName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用外键从另一个列表中获取值? - How do I use a foreign key to get a value from another list? 如何在下拉列表项中显示关联的值(从列表中选择后)? - How do I show an associated value with a dropdown list item (after choosing it from the list)? 如何从外键关联表中获取数据列表是mvc中的json格式 - How to get list of data from foreign key associated table is json format in mvc 如何在控制器操作中获取实体以填充外键对象的值? - How do I get Entity to populate the values of foreign key objects at the controller action? 如何从带有反射的嵌套列表中获取价值? - How do I get value from a nested list with reflection? 如何获得外键上的“ NameOf”? - How do I get the “NameOf” on a Foreign Key? 当值是列表时如何从字典中获取键,值 - How to get Key, Value from dictionary when value is a list MVC 5从另一个表填充下拉列表并保存值NOT KEY - MVC 5 populate dropdown list from another table and save value NOT KEY 如何从组合框中选择一个值以在 c# 中显示关联的值 - How do I select a value from a combo box to display an associated value in c# ASP.NET 使用关联的外键文本值填充下拉列表 - ASP.NET Populating Dropdown with associated foreign key text value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM