Friday, 8 October 2010

Extending SPMetal - Retrieving Attachments from SharePoint Lists

Problem: LINQ to SharePoint does not support attachments by default.
Hypothesis: Traditional Server Object Model approach to retrieving a specific list item’s attachments.  Approach is shown below:
Resolution: Use a partial class as described by Andrew Connell to use Linq to SharePoint to work with attachments. You could hydrate the attachment (SPFile objects) in the parital class but I choose not to, in case someone in the development team used the extended mapped property for retrieving a large list. This uses the Server object model and the hydration process is extremely heavy.  This method allows me to know if there are attachments, how many and where I can get them.  With this information I only get the specific SPFile objects if I need to work with the object.  Outlined are the steps to extend LINQ to SharePoint to retrieve attachment associated to items in a list.

1) Extend the SPMetal generated proxy class
2) Get a specific item using the LINQ to SharePoint model and using the String array returned by the extended class, get the file objects using SharePoint’s server side object model.
Tip: attachments is a string array, not an array of SPFile objects. The attachements.UrlPrefix property can be used to hydrate the SPFile objects for the list item.

Tip: I upload attachments using the Dialog framework point to attachfile.aspx as it does all the work for me.


Anonymous said...

The code fails when you use Linq to sharePoint to update the list. Commenting out the MapTo() method's code makes the SPMetal class read/write with the exception that you can write back attachments. - PaulB

Post a Comment