Skip to content

Instantly share code, notes, and snippets.

@DForshner
Created September 18, 2013 22:41
Show Gist options
  • Save DForshner/6616764 to your computer and use it in GitHub Desktop.
Save DForshner/6616764 to your computer and use it in GitHub Desktop.
Using Sum() with Linq-2-Entities navigation properties.
// Fixes error: The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.
// In the case where none of the navigation property's StringPropA properties match a null will returned.
// .Sum() will throw an error if you try to sum null so we replace the null with a default value using .DefaultIfEmpty()
var total = Parent
.Where(x => x.NavigationProperty.StringPropA == "Foo")
.Select(x => x.DecimalPropB)
.DefaultIfEmpty(0)
.Sum()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment