Tuesday, May 11, 2010

Insert item into a (sub) folder using Linq to Sharepoint

Someone had a question on how to insert items into a sub folder of a list in SharePoint 2010 when using Linq. Not obvious at first, I thought I'd blog the answer:

Let's say that you Create someObject based on a class generated by SPMetal. Let's also say that this object is suitable for passing to the InsertOnSubmmit method of the data context. Then you call the following to insert the item into the root of the list:


dataContext.SomeList.InsertOnSubmit(someObject);


Now you want to insert that item into a folder in the list, called Folder1. What you need to do is use the Path property on the someObject. This property is present if you use SPMetal to generate the Linq classes.

I created a folder in my SomeList called Folder1, and then I set the Path property like so:


mynewObject.Path = "/Lists/MyList/Folder1";


Then call the InsertOnSubmit method as usual and your item will be in the right folder! I am not yet sure how to create the folder through linq, and do note that exceptions are thrown if the folder is not there. I'll try to solve that one in a later post.

7 comments:

Unknown said...

Thanks Joe

Unknown said...

Thanks Joe

Unknown said...

How can we get the records from folder inside the list by using the SPMetal

Thanks in Advance!
Regards,
Vishal

Joe said...

SPMetal and folders are discussed at this post: http://sharepoint.stackexchange.com/questions/17574/unable-to-get-document-set-inside-document-library-using-linq-to-sharepoint-entit

Unknown said...

Thanks very much.

Unknown said...

Hi Joe,

We are trying to insert a record in the folder of list as suggested by you. But we are getting following error
"Invalid file name.

The file name you specified could not be used. It may be the name of an existing file or directory, or you may not have permission to access the file.
"
It comes when we give the folder path in path property

Regards,
Vishal

Joe said...

I am not sure why you are getting that error. Post your questions and a code sample in the forum at http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010programming/threads and I or someone else can help out.