简体   繁体   English

实体框架 - 根据另一个表中的 ID 获取实体名称

[英]Entity Framework - Get name of entity based on ID from another table

I'm not sure how to phrase this question correctly but here's an issue I am currently facing in a backend development project.我不确定如何正确表达这个问题,但这是我目前在后端开发项目中面临的一个问题。

Suppose I have a table called Users.假设我有一个名为 Users 的表。 I create a model called User:我创建了一个名为 User 的模型:

public partial class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public id JobTitleId { get; set; }
        ... other fields
    }

A user has a Job title which is related to a JobTitles table.用户具有与 JobTitles 表相关的职位。 The way its structured now is the FE will call an api, lets call it dictionary api which returns a list of objects with the job titles.它现在的结构方式是 FE 将调用一个 api,让我们称之为字典 api,它返回一个带有职位名称的对象列表。 So, something like this: [{id: 1, title: 'aa'}, {id: 2, title: 'bb'} ...] So, based on the jobtitleid that was available, this api will be called and the view will show the title based on the id.所以,像这样: [{id: 1, title: 'aa'}, {id: 2, title: 'bb'} ...] 所以,基于可用的 jobtitleid,这个 api 将被调用和该视图将根据 id 显示标题。

Now, I feel like this is not really efficient since if we have a hundred or thousand job titles, FE will have to parse through each object to match the id.现在,我觉得这不是很有效,因为如果我们有一百或一千个职位,FE 将不得不解析每个对象以匹配 id。

Is there a better way to display the name of the job title given the ID?有没有更好的方法来显示给定 ID 的职位名称? I cannot return the job title directly because if the user's job title is not updated but that particular form with the job titles is sent with a PUT request, it will return the name of the job title instead of the ID back to the users table.我不能直接返回职位,因为如果用户的职位没有更新,但是带有职位的特定表单随 PUT 请求一起发送,它将返回职位名称而不是 ID 到用户表。

Also, the job title will be an autocomplete field on the Frontend which will call an api on the backend when a user inputs the name of the job title, thereby returning the id of that job title back to the Backend when a user is updated with a new job title.此外,职位名称将是前端的自动完成字段,当用户输入职位名称时,它将调用后端的 api,从而在用户更新时将该职位的 id 返回给后端一个新的职位。

Sorry if Im not clear enough, I can ive more details if required.抱歉,如果我不够清楚,如果需要,我可以提供更多详细信息。

have you tried doing something like this?你试过做这样的事情吗? I am assuming JobTitleId belongs to JobTitles class我假设 JobTitleId 属于 JobTitles 类

public partial class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public id JobTitleId { get; set; }

    [ForeignKey("JobTitleId")]
    public JobTitles JobTitles{ get; set; }
}

so as you know classes are object by reference and when you pass the User class to your view, the moment you change the user title from the dropdown it will also change the jobtitleId accordingly所以你知道类是引用对象,当你将 User 类传递给你的视图时,当你从下拉列表中更改用户标题时,它也会相应地更改 jobtitleId

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM