In SharePoint 2010 you can use LINQ to insert items into a list like this:
using (var context = new DataEntitiesDataContext(http://localhost/))
{
var item1 = new MyListItem();
item1.Comment = “Item 1”;
var item2 = new MyListItem();
item2.Comment = “Item 1”;
context.MyList.InsertOnSubmit(item1);
context.MyList.InsertOnSubmit(item2);
context.SubmitChanges();
}
You might be forgiven to ponder whether the above code would support transaction. I know I did! (especially after a user group presenter told me that yes it would).
I tried it out and it doesn’t.
I guess I shouldn’t have even thought about it, since this is being translated to CAML at the end of the day.
It still remains that if you require transaction support, then SharePoint is not for you :D.
One interesting thing I picked up during testing is that the code correctly raised exceptions on column validation errors and unique constraints – but did not fail on required fields. It happily inserted the item into the list with the required fields missing.
Great article but I have a question on InsertOnSubmit.
What if you have a Lookup field on MyList which is for example MyListType that looks up on MyListType List how would I do this now?
using (var context = new DataEntitiesDataContext(http://localhost/))
{
var item1 = new MyListItem();
item1.Comment = “Item 1″;
item1.MyListType = ???????????????????
as MyListType will be or MyListTypeItem type.
Hey rsmacaalay,
When you generate your data entities mapping file using SPMetal it will generate strongly-typed associations for you between your entity classes. So in your scenario, it would create for you a MyListItem class and a MyListTypeItem class. (Although if you did not add any extra column to your MyListType list, then you would have the class Item created for you).
Your MyListItem class would have a property MyListType, and it would be of type MyListTypeItem. To set this property, you’d need something like this:
//First get the MyListType item that you want to set the value to.
var listType = (from type in context.MyListType
where type.Id == 3
select type).FirstOrDefault();
//Now create the item to insert
var item = new MyListItem();
item.Title = "Hi World";
item.MyListType = listType;
context.MyList.InsertOnSubmit(item);
context.SubmitChanges();
For further information, check this link: http://msdn.microsoft.com/en-us/library/ff798478.aspx.
Hope this helps.