linq from a list inside a class

Anjali Agarwal 1,531 Reputation points
2023-02-08T23:51:11.5733333+00:00

i have the following Model class:

public partial class EmployeeInfo

{

public int EmployeeInfoId { get; set; }

public string FirstName { get; set; } = null!;

public int? JobTitleLookupId { get; set; }

public virtual JobTitleLookup? JobTitleLookup { get; set; }

}

public partial class JobTitleLookup

{

public int JobTitleLookupId { get; set; }

public string Title { get; set; } = null!;

public virtual ICollection<EmployeeInfo> EmployeeInfos { get; } = new List<EmployeeInfo>();

}

I have JobTitleLookupId in my employeeeInfo database table. How can i get

the name of the jobtitle if i have the corresponding ID in employeeInfo Table.

belows is my JobTitleLookup table:

JobTitleLookupID   title
1                   title1
2                   title2
3                   title3

EmployeeInfo table

EmployeeInfoId FirstName JobTitleLookupID
1                test1     2
2                test3     1
3                 testx     3

how can I get Title using LINQ if I query the employeeInfo table.

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-02-09T01:59:21.9+00:00

    Hi @Anjali Agarwal

    I have JobTitleLookupId in my employeeeInfo database table. How can i get the name of the jobtitle if i have the corresponding ID in employeeInfo Table. how can I get Title using LINQ if I query the employeeInfo table.

    You can get the job title according to the Navigation property: JobTitleLookup.

    The LINQ query statement as below: use Inculde method to load the related entity. More detail information, see Eager Loading of Related Data.

                var id = 2;
                var query = _dbcontext.EmployeeInfos
                            .Include(c => c.JobTitleLookup)
                            .Where(c => c.EmployeeInfoId == id)
                            .Select(c => new
                            {
                                EmployeeInformId = c.EmployeeInfoId,
                                FirstName = c.FirstName,
                                Title = c.JobTitleLookup==null?"null":c.JobTitleLookup.Title
                            }).ToList();
    

    The result as below:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.