onsdag den 20. august 2014

Creating a new item with a specific ID instead of an auto-generated one.

Normally, when you create an item from code, you find the parent item, and use the Add method on this item to create the child.

This is the recommended way to create items, however - it misses one crucial thing, which is defining what ID the newly created item has.

The logical question to ask is - why would you want to deside which ID the item has?
The answer is - alot of times when you import data from something where the unique ID already is a GUID.

The reason for this is, that is makes it very fast to lookup if the item already exists, and easy to handle cross-references between items.

Also, if you are migrating items from one Sitecore instance to another by code (as in - creating new items, not copying the old items over) - keeping the ID's might be a good idea, to again make cross-references work.

Enough walk you say? Okay, here is how to do it:

// The name of the item to be created.
string newItemName = "My New Item";

// Some way to get the parent item.
Item parentItem = GetItemParent();

// The ID of the template to create the item from - can be a branch ID.
ID templateID = new ID("{1618FA40-8E57-4018-968A-5996E4952D93}");

// The ID of the item to be created.
ID newItemID = new ID("{9AAFC1F7-F276-4651-ADD2-6C9ED6F1B9E0}");

// Should security for the operation be checked?
SecurityCheck checkSecurity = SecurityCheck.Enable;

// Now we create the item.
Item newItem = ItemManager.CreateItem(newItemName, parentItem, templateID, newItemID, checkSecurity);

Now we have created an item, with the ID defined in newItemID.

Pretty simple, don't you think?

Ingen kommentarer:

Send en kommentar