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

.net-core c# entity-framework entity-framework-core

Question

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. I create a model called 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. 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. 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.

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.

Is there a better way to display the name of the job title given the 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.

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.

Sorry if Im not clear enough, I can ive more details if required.

1
3
3/13/2020 5:11:10 AM

Popular Answer

have you tried doing something like this? I am assuming JobTitleId belongs to JobTitles class

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

0
3/13/2020 8:26:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow