How to programmatically populate Sitecore items (A

2019-06-23 02:28发布

I'm now battling with adding items via C# to Sitecore database.

The code below executes correctly, however the items aren't being created.

Also, I noticed, that the item["FieldName"]=value; syntax doesn't actually populate the Fields collection.

And Fields collection on the item seems read only, so I can't just call .Add on it (such method doesn't exist).

So - what is the correct way of creating a child item and populating its fields?

I am using the Master database for both the Sitecore backend and this code.

The code I use below:

   using (new Sitecore.SecurityModel.SecurityDisabler())
   {

        Database db = Factory.GetDatabase(this.Database);

        foreach (var vacancy in Articles.Tables[0].Rows)
        {
            var rootItem = db.GetItem(this.RootItem);
            DataRow dr = (DataRow) vacancy;

            var newItem = rootItem.Add(string.Format("{0} {1}", dr["numericID"], dr["job_name"]),
                                       db.GetTemplate(new ID("{GUID}")));

            newItem.Editing.BeginEdit();
            newItem["Job Title"] = dr["job_name"].ToString();//
            newItem.Editing.EndEdit();
        } 
}

More info: newItem.Template.Fields returns a collection with 100 fields

newItem.Fields returns a FieldCollection with only 9 elements in it.

When I pass through the code newItem["field"].Value = value; it does not increment the newItem.Fields collection count.

Of course the "field" key is consistent with ones present in newItem.Template.Fields[x].Name.

3条回答
Ridiculous、
2楼-- · 2019-06-23 02:42

I would recommend two changes:

(1) The item naming approach:

var newItem = rootItem.Add(ItemUtil.ProposeValidItemName(string.Format("{0} {1}", dr["numericID"], dr["job_name"])), db.GetTemplate(new ID("{GUID}")));

This change will handle invalid characters in the proposed name from your other data source.

(2) The field value setting approach:

newItem.Fields["Job Title"].Value = dr["job_name"].ToString();

This will set the raw value of the field to the provided string.

查看更多
forever°为你锁心
3楼-- · 2019-06-23 02:43

1) Check some things first f.ex:

assing the template to a variable and check what you get there. and better don't do it by ID rather by path:

var templateItem = db.GetTemplate("yourTemplatePath");

now check whether that is the template you want? make sure it's published (it can always cause some inconsistencies)

2) As to the fields not being 'visible', have you tried: item.Fields.ReadAll()

3) What do you mean by "items not being created"? how would you check that?

4) Also - are you sure that this.Database == "master" ?

查看更多
不美不萌又怎样
4楼-- · 2019-06-23 02:43

I would suggest setting the field value as

newItem.Fields["Job Title"].Value = dr["job_name"].ToString();//

Everything else looks ok.

查看更多
登录 后发表回答