1

I am writing a plugin which will essentially perform the same function - say, create a task when the status changes. The functionality needs to happen on 2 entities.

Every step is exactly the same except setting of the Entity Type field (an Option Set). This is set to EntityA or EntityB depending upon which entity triggered the plugin.

My existing code does the following

new_entitya entityA = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && context.PrimaryEntityName == "new_entitya")
                                    ? ((Entity)context.InputParameters["Target"]).ToEntity<new_entitya>()
                                    : null;

Now, is there a way that I can set the value of .ToEntity call based on the value of PrimaryEntityName instead of writing new_entitya or new_entityb?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Kanini
  • 1,947
  • 6
  • 33
  • 58

2 Answers2

2

Why cast at all? You can just check the entity name and apply whichever property you need to.

var newTask = new Entity("Task");
newTask.Attributes.Add("subject", "foo");
// etc etc for other common properties
if (context.PrimaryEntityName.Equals("new_entitya"))
{
    newTask.Attributes.Add("new_optionset", valueA);
}
else
{
    newTask.Attributes.Add("new_optionset", valueB);
}

I guess the downside is that you have to maintain the optionset values in the plugin but doesn't seem a huge overhead if it is just two values.

glosrob
  • 6,631
  • 4
  • 43
  • 73
  • +1 Late bound is much better in this scenario. The early bound wrapper isn't always the best option. If you need to start thinking about using reflection, you're doing it wrong. – Darren Lewis Apr 27 '13 at 13:50
0

Refer to this post. Basically you have to build a generic method on the fly based on the type passed in.

Community
  • 1
  • 1
Daryl
  • 18,592
  • 9
  • 78
  • 145
  • 1
    So should it be closed as duplicate? – Paul Bellora Apr 26 '13 at 18:18
  • @PaulBellora Yes and no. The question is phrased the way a CRM Developer would ask it, so it would be helpful for them to find it... but theoretically the question is really the question that I linked to... – Daryl Apr 26 '13 at 18:42