Plugins: Getting an Entity's Record Id in the Pre-Create Stage
If you ever have a need to work with the record id of a particular record during a pre-create stage with your plugin, then this post is for you. The title is a little misleading, though - you cannot actually get the Guid of a CRM record before that record is created. What I've found is that instead of trying to get the record id, you can create it. Here's how:
Let's say we have our plugin and we have grabbed the data being saved. What we'll do is create a new KeyProperty and add that to the entity's properties collection:
// Grab the entity record
entity = (DynamicEntity)context.InputParameters.Properties["Target"];
// Create the record id
string sKeyAttribute = entity.Name + "id";
Guid oGuid = System.Guid.NewGuid();
KeyProperty oKey = new KeyProperty(sKeyAttribute, new Key(oGuid));
// Add the record id to the properties
entity.Properties.Add(oKey);
That's it. You've created your own record id. Of course, now you can subsequently use the value of oGuid in your code. I've used this in the 4.0 environment and it's worked well so far. What I imagine CRM is doing when the record is created is checking for the existence of the key property and only creating it when it is not present. I'm not really sure if it's documented or an intended behavior, but it's a nice piece of functionality.
So why go this route instead of waiting and doing a post-create plugin? Well, I like this method because it involves no additional web service calls (getting the service, retrieving the entity, updating, etc) as long as you aren't touching other entities.

Does this code work for form OnLoad event?
Posted by: D.Ilyin | March 23, 2009 at 07:13 AM
It would not. Furthermore, we've starting seeing some issues with this technique on entities where there are duplicate detection rules being enforced.
Posted by: Will Wilson | March 25, 2009 at 04:12 PM