Im hoping someone can help me with a brain block I’m having about how to do multiple joins with EF that returns an entity, where one of the fields is calculated by a query. Ive contrived a (pretty much useless) example in the hopes somebody can help me understand how this should be done.
Id like to return a list of ISPs entities from a DBContext with the “TotalUsed” property filled in by the LINQ query. Ive successfully done the joins (trivial), and have played with grouping and sum, but cant seem to get it quite right.
The general idea to this contrived example is that NICs are connected to one and only one router, and multiple routers are connected to a single ISP each.
How to write a LINQ query that sums the bandwidth needed for each ISP, along with the other properties in that ISP?
Expected output would be a list of ISP that might look like
{{1, “foo”, 52}, {2, “bar”, 345}, {3, “foobar”, 621}}, where the 3rd property is the summation of the BandwidthNeeded property on all NICs transitively related to ISP.
The classes:
public class ISP
{
public int ISPid {get; set;}
public int ISPName {get; set;}
public int TotalUsed {get; set;} // not mapped to DB -> should populate via LINQ
}
public class Router
{
public int RouterId {get; set;}
public string RouterName {get; set;}
public int ISPId {get; set;} // foreign key for ISP
}
public class Nic
{
public int NicId { get; set; }
public string NicLocation { get; set; }
public int BandwidthUsed { get; set; }
public int RouterId {get; set; } // foreign key for router
}
If you move the TotalUsed property into a separate type, you could do this (please excuse any typos):
If you add navigation properties, it could be made somewhat more readable by removing the links on ID.