I am trying accomplish creating a c# statement dynamically to avoid the use of the switch statement shown below. I looked into CodeSnippetStatement class but could not make it work.
dynamic apps;
switch (entity)
{
case "entity_1":
apps = Xrm.Entity_1Set.SingleOrDefault(a => a.Id.Equals(guid));
break;
case "entity_2":
apps = Xrm.Entity_2Set.SingleOrDefault(a => a.Id.Equals(guid));
break;
case "entity_3":
apps = Xrm.Entity_3Set.SingleOrDefault(a => a.Id.Equals(guid));
break;
…
I would like to do something like this (pass entity dynamically into string and convert the statement to execute in run time):
apps = CodeSnippetStatement(String.Format(“Xrm.{0}Set.SingleOrDefault(a => a.Id.Equals(guid)”, entity) );
Is that possible??
Assuming
Entity_1Setis a public property ofXrm, you could use reflection:This will only work if
Xrmis an instance of a class (not a static class reference).Note that reflection is slower than direct access of a property. This time cost is not much if you are only doing this occasionally. But inside a loop, it could add up.
Another technique would be to cache your EntitySet instances into a dictionary:
Then you would just need to do: