I have an interface like what u see below and I want it to return me a Property Called "ProductionCostId" which has a type of 'int' from a table in the database
int Get(Guid productionLineId, string productionCode)
In the implementation as you can see I want to get this value from a child entity called "ProductionAssignmetnt"
public int Get(Guid productionLineId, string productionCode)
{
return GetAll()
.Where(x => x.ProductionAssignments
.Where(x => x.ProductionLine.Id == productionLineId && x.ProductionCode == productionCode)
.Select(x => x.ProductionCostId);
}
But I dont know how to get this int value
CodePudding user response:
First, you need to include the productionassignments table to this query i.e. join it.
In your GetAll()
method where you return in you can join a table using code first by _context.ProductionLines.Include(x => x.ProductionAssignments)
, if you're on Database First then read this on how to join tables
Now since you haven't posted any model, this is how you'd select if your ProductionCostId
is nested inside the assignments
GetAll()
.FirstOrDefault(pLine => pLine.Id == productionLineId)
?.ProductionAssignments.FirstOrDefault(assignment => assignment.ProductionCode == productionCode)?.ProductionCostId)
This query will get the production line with the id, and then select the first productionCostId
from the assignments where the code matches. This query assumes the Model
public class ProductionLine
{
public int Id {get;set;}
public List<ProductionAssignment> ProductionAssignments {get;set;}
}
public class ProductionAssignment
{
public int ProductionCode {get;set;}
public int ProductionCostID {get;set;}
public ProductionLine ProductionLine {get;set;}
}
Beware of null reference exceptions.
CodePudding user response:
You can achieve this by using .Any statement to filter and then can get ProductionCostId directly from Your main object.
public int Get(Guid productionLineId, string productionCode)
{
return GetAll()
.FirstOrDefault(x => x.ProductionAssignments.Any(y => y.ProductionLine.Id == productionLineId && y.ProductionCode == productionCode))
?.ProductionAssignments.FirstOrDefault()?.ProductionCostId ?? 0;
}