Search code examples
c#entity-frameworklinq-to-entities

how to use joining with LinQ To Entity


I have this code

    var value = (from dc in _context.ContractDetails
                   where dc.EmployeeID == id
                    select dc.Amount);
    return value;
}

is it acceptable to do Value.Sum();


Solution

  • You want to return the sum it looks like. Instead of having query be a decimal, just let it be what it wants (var, it's really IEnumerable<decimal>). Then you can return an aggregate on that. Sum for example

    var query = from emp in Employees
                join cd in ContractDetails
                on emp.EmployeeID equals cd.EmployeeID
                where cd.EmployeeID == id
                select cd.Amount;
    return query.Sum();
    

    If this is all it does, then I also feel like you don't need to join at all, and it would be simpler to do

    var query = from cd in ContractDetails
                where cd.EmployeeID == id
                select cd.Amount;
    return query.Sum();
    

    ... unless you were using the join to test for the existence of an employee in the Employee table as a condition.