I’ve been putting together an auditing solution for a program I am developing, where I am using LINQ for my update/insert operations. I have come up with the following solution (this is the snippet for inserting) (Note the Tables variable contains a list of all the tables that have been modified – I add these to the list manually and call this method):
BindingFlags b = BindingFlags.Instance | BindingFlags.Public;
LINQDataContext dc = new LINQDataContext();
foreach (object Table in Tables)
{
string TableName = Table.ToString().Replace("Project.", "");
switch (TableName)
{
case "Job":
string NewJobString = null;
Job JobDetails = (Job)Table;
var prpsJob = typeof(Job).GetProperties(b);
foreach (var p in prpsJob)
{
object x = p.GetGetMethod().Invoke(JobDetails, null);
x = StripDate(x);
NewJobString += p.Name + ": " + x + Environment.NewLine;
}
Audit(JobID, NewJobString, "New Job created", SourceID, "", JobDetails.JobID);
break;
case "Estimation":
string NewEstimationsString = null;
Estimation EstimationDetails = (Estimation)Table;
var prpsEstimations = typeof(Estimation).GetProperties(b);
foreach (var p in prpsEstimations)
{
object x = p.GetGetMethod().Invoke(EstimationDetails, null);
x = StripDate(x);
NewEstimationsString += p.Name + ": " + x + Environment.NewLine;
}
Audit(JobID, NewEstimationsString, "New Estimation created", SourceID, "", EstimationDetails.EstimationID);
break;
And the code goes on for each possible tablename. The code works fine, but it seems fairly inefficient – having a nearly identical block for each case. Is there a more efficient way?
You should be able to use Lambdas to cover the type-specific parts of the repeated code. This is some almost pseudo-code I hacked together….
And then you can replace your huge for loop and switch case with…
This is all assuming that “efficient” means in terms of code volume, not in execution time.