Here is a question I frequently ask myself. Here is a code with no repeated code:
private static void delete(Guid teamID, Guid repID)
{
using (var context = AccesDataRépart.GetNewContext())
{
Team_Representant teamRepresentant = getTeamRep(teamID, repID);
if (teamRepresentant != null)
context.Team_Representant.DeleteOnSubmit(teamRepresentant);
context.SubmitChanges();
}
}
private static Team_Representant getTeamRep(Guid teamID, Guid repID)
{
using (var context = AccesDataRépart.GetNewContext())
{
return (from c in context.Team_Representant
where c.RepID == repID &&
c.TeamID == teamID
select c).FirstOrDefault();
}
}
It is normal to have a getTeamRep function, it is used very often. On the other hand, I don’t repeat the query it contains in the Delete function because it would generate extra steps and would generally be slower.
What do you do in such case? Do you repeat the getTeamRep linq query in the Delete function or do you accept this extra workload?
Thanks!
I never do anything twice :). Make a variable to hold the result of getTeamRep.
If you’ve never tried it before, get rid of your static stuff and make these all instance methods. Have a Team class and a Rep class, and let the Teams contain their Reps. It might be more fun this way, and it tends to prevent the whole problem of looking up the same object twice.
It’s a matter of preference. I find instance methods more elegant in most cases, because there are fewer parameters: