LINQ from a list inside a class - linq

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.
below 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 the job title if I have the employeeinfoId and jobTitleLookupID using LINQ.'
this is what I tried so far:
public async Task<List<string?> GetJobTitle(string employeeId)
{
var query = _ackContext.EmployeeInfos
.Include(c => c.JobTitleLookup)
.Where(c => c.EmployeeNumber == employeeId)
}
this is something I wrote in sql. I want the same in LINQ
SELECT
title
FROM
employeeInfo e
INNER JOIN JobTitleLookup j ON
e.JobTitleLookupID =j.JobTitleLookupID
AND
EmployeeInfoID = 212;

To select something precise, you have to use Select.
public Task<List<string?> GetJobTitle(string employeeId)
{
return _ackContext.EmployeeInfos
.Where(c => c.EmployeeNumber == employeeId)
.Select(c => c.JobTitleLookup.Title)
.ToListAsync();
}

Related

Fluent LINQ EF Core - Select filtered child property

I have the classes below:
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class ParentEntity
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public ICollection<ChildEntity> ChildEntities { get; set; }
}
public class ChildEntity
{
public Guid Id { get; set; }
public int Vote { get; set; }
public Guid UserId { get; set; }
}
public class ReturnedParentDto
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public int Vote { get; set; }
}
I want to be able to return a full list of ParenEntities, but take an Id of the User class (UserClassId), then filter the ParentEntity's ICollection where UserUid = UserClassId, so only 1 ChildEntity is always returned. Then I would want to extract a specific field from that returned ChildEntity and merge it with the ParentEntity fields. The end result should be like the ReturnedParentDto.
I want to do it in the style like
ParentEntities.Include(v => v.ChildEntities).ToList()
That seems to be possible in EF Core 5, but my project is in 3.1.
You can do this as below
Approach 1:
var result = result = parentEntities.Include(x => x.ChildEntities.Where(y => y.UserId == userId))
.Select(x => new ReturnedParentDto {
Id = x.Id,
SomeProperty = x.SomeProperty,
Vote = x.ChildEntities.FirstOrDefault()?.Vote // userId is the variable here
});
Approach 2:
var result = parentEntities.Select(x =>
new ReturnedParentDto {
Id = x.Id,
SomeProperty = x.SomeProperty,
Vote = x.ChildEntities.FirstOrDefault(y => y.UserId == userId)?.Vote // userId is the variable here
});

How to join 3 tables in linq and get some not included fields in query

I'm implementing asp.net core project. I have 3 tables Apiapp, ApiAppHistory and EntityType. There are three fields with the names SentType, Status and Reason in ApiAppHistory and those fields are of kind Id (int type) in APIApphistory. I joined ApiApp and ApiAppHistory tables in order to get those three fields from ApiAppHistory but because they are of kind int and are unclear when showing the result to the user, I join them with EntityType table which has their related name. In the select part of my query, in addition to ApiApp fields I also need to have SentType, Status and Reason value fields.
Here below is my incomplete query:
var qq = _context.Apiapp
.Include(a => a.Api)
.Include(a => a.Application)
.Include(a => a.Data);
var t12 = (from r in qq
from b in _context.ApiAppHistory
from s in _context.EntityType
where r.LastRequest== b.Id && b.SentType == s.Id
&& b.Reason == s.Id
&& b.Status == s.Id
select new { r, s.name for Reason, s.name for
SentType ,s.name for Status});
I want in select part of my query, obtain name of the fields that I specified from the EntityType table. However, I don't know how to do it. I appreciate if someone helps me.
Here is my EntityType table:
Here are my APIAppHistory and EntityType class model:
public partial class ApiAppHistory
{
public int Id { get; set; }
public int? SentType { get; set; }
public int? Reason { get; set; }
public int? Status { get; set; }
public virtual Apiapp ApiApp { get; set; }
public virtual EntityType StatusNavigation { get; set; }
public virtual EntityType SentTypeNavigation { get; set; }
public virtual EntityType ReasonNavigation { get; set; }
}
public partial class EntityType
{
public EntityType()
{
ApiAppHistoryStatusNavigation = new HashSet<ApiAppHistory>();
ApiAppHistorySentTypeNavigation = new HashSet<ApiAppHistory>();
ApiAppHistoryReasonNavigation = new HashSet<ApiAppHistory>();
}
public int Id { get; set; }
public string Name { get; set; }
public string EntityKey { get; set; }
public virtual ICollection<ApiAppHistory> ApiAppHistoryStatusNavigation { get; set; }
public virtual ICollection<ApiAppHistory> ApiAppHistorySentTypeNavigation { get; set; }
public virtual ICollection<ApiAppHistory> ApiAppHistoryReasonNavigation { get; set; }
}
}

Linq Query Help on outter join against a list in and object

I have the following object Job and Job sor are populated by reading in data from an XML file and Sor is populated from a database.
class Job
{
public int JobID { get; set; }
public string DepartmentCode { get; set; }
public string ClientReference { get; set; }
public string JobDescription { get; set; }
public List<JobSor> JobSorList { get; set; }
}
class JobSor
{
public int JobID { get; set; }
public string SorUserCode { get; set; }
public string SorNotes1 { get; set; }
public string SorNotes2 { get; set; }
}
class Sor
{
[Key]
public string code { get; set; }
public string description { get; set; }
public string contract { get; set; }
}
I want to write a linq query that will show me all the JobSors that do not exist in the Sor object.
This is what I have so far but I can’t reference the SorUserCode property?
var db = new dbContext();
var sor = db.Sors.Where(p => p.contract == "??");
var query =
from j in jobs
join p in sor on j.JobSorList.SorUserCode equals p.code into jp
from a in jp.DefaultIfEmpty()
select j;
How can I do this?
First get list of all JobSor from jobs list.
Then apply condition Where its SorUserCode value does not match with Any code value of the sor list.
Your query will be as below.
var query = jobs.SelectMany(x => x.JobSorList)
.Where(x => !sor.Any(y => y.code == x.SorUserCode));

Complex LINQ or EF query

I have the following 3 classes.
A workflow configuration has one brand and one workflowtype.
I need one method in linq or EF that gets me all the brands of existing workflowconfiguration and another method that gets me all the brands of non existing workflow configuration.
I am lost cause I dont know where to start.
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
}
public class WorkflowType
{
public int WorkflowTypeId { get; set; }
public string Name { get; set; }
}
public class WorkflowConfiguration
{
public int WorkflowConfigurationId { get; set; }
public WorkflowType WorkflowType { get; set; }
public Brand Brand { get; set; }
public virtual ICollection<Approver> Approvers { get; set; }
}
Update1
Here are how my tables would look like and the expected result
Brand
Audi
Volkswagen
Mercedes
WorkflowTYpes
type 1
type 2
type 3
WorkflowConfiguration
brandid, workflowtype id
1 ------------ 1
1 -------------2
List<string> GetBrandsForExistingWorkflowType(string worfklowtype)
If I pass type1 to this method it should return:
Audi because for type1, audi exists on the table
List<string> GetBrandsForNonExistingWorkflowType(string workflowType)
If I pass type1 to this method it should return.
Volkswagen and Mercedes because for type1, those 2 brands are not in the relationship.
I think this is what you want:
List<string> GetBrandsForExistingWorkflowType(string worfklowtype)
{
var result = db.WorkflowConfigurations
.Where(x => x.WorkflowType.Name == worfklowtype)
.Select(x => x.Brand);
return result;
}
List<string> GetBrandsForNonExistingWorkflowType(string workflowType)
{
var excluded = GetBrandsForExistingWorkflowType(string worfklowtype);
var result = db.Brands.Except(excluded);
return result;
}

How to get Users who only have some specific department id, Linq

I have following two entities
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public List<Department> Departments { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public List<User> Users { get; set; }
}
As you see, relationship between two objects is M:N.
I wanna get User who only have specific department ID, in this case, How to get users using Linq?
Thanks in advance
int requiredId = ...
var usersInReqdDept = Users.Where(u => u.Departments
.Any(d => d.DepartmentId == requiredId));
If the Departments list can be null, you will need a null-check in the Where clause.
If you want to search the Departments list instead,
int requiredId = ...
var usersInReqdDept = Departments.Single(d => d.DepartmentId == requiredId)
.Users;
Of course, this will throw an exception if such a department doesn't exist.

Resources