I am trying to learn Entity Framework. I am happy that the results I am returning from my queries are giving me the data that I need but I find that I am using allot of for-each loops and separate database requests to get the information I require.
I would be grateful if someone could review my code and advise if there is a way I could make things more concise and also if I am not really getting the functionality that the entity framework offers ( I think I am missing the point here somewhere!!!). Any way here is the problem and the code (which I hope makes sense):
Attempting to query from 4 tables in my database. One is unrelated (due to my laziness - I need to amend this but it is not a deal breaker at present). The other 3 are related with a 1 to many relationship. here is a summary:
UserClients - unrelated table (should be linked to LeadClient but not important)
[LeadClient PK = GroupCode] one to may to [Matters FK = LeadCode] [Matters PK = MatterNumber] one to many to [Invoices FK = Matter]
I am attempting to create a list of DTO objects to populate a GridView. My DTO is as follows:
public class dto
{
public string clientCode { get; set; }
public string clientName { get; set; }
public decimal totalDebt { get; set; }
}
I am passing in a statementName variable to a method which I then query against UserClients to get a List of clientcodes.
Here is my method to populate my List objects:
public static List<dto> StateNameLeadCodes(string stateName)
{
//DTO objects
List<dto> items = new List<dto>();
//Leadcode list for statement name
List<string> leadcodes = (from o in repository.UserClients where o.StatementName == stateName select o.LeadCode).ToList();
//From leadcodes populate items list
foreach(string s in leadcodes)
{
//Get clientCode and matter list for the client code
var code = (from o in repository.LeadClients where o.GroupCode == s select new { o.ClientName, o.Matters}).First();
dto temp = new dto();
temp.clientCode = s;
temp.clientName = code.ClientName;
//Get a list if invoices for each matter
foreach (Matter m in code.Matters)
{
List<Invoice> invoices = (from o in repository.Invoices where o.Matter == m.Matternumber select o).ToList();
//Calculate total debt for all invoices
foreach (Invoice inv in invoices)
{
temp.totalDebt += (inv.debt_Fee + inv.debt_Costs + inv.debt_VAT);
}
}
items.Add(temp);
}
return items;
}
I find myself doing something similar when I want to return a combination of a single item and a list to a DTO. I see that my Entity classes have an EntityCollection for the One to Many relationship. I have tried to select the entity object as part of my select statements but I get the error that the EnitityCollection cannot be converted to a List<>.
Any tips and pointers how to clean this code up would be great - thanks in advance!!
Added image of Entity objects as requested: