0

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

habib
  • 2,366
  • 5
  • 25
  • 41

1 Answers1

0

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.

AMunim
  • 992
  • 6
  • 13
  • I think he doesn't have ProductionLineId in the main parent table, that's why he was not filtering it directly. Instead, he applied filters on child collections. – habib Jun 08 '22 at 09:19
  • I think he did because in his PrductionAssignments he has a fields `ProductionLine` for which he matches the Id – AMunim Jun 08 '22 at 09:28
  • thank you guys, your comments were really helpful, the problem fixed – HassanJalali Jun 08 '22 at 11:37