5

I've used SPMetal to generate my DataContext and classes for my custom Content Types. Some of these Content Types derive from Document content type.

I need to run a Linq query against a Document Library and access the binary data for each of the files returned. The documents are returned nicely as the expected Entity types.

My problem is that I can't really figure out how to do the equivalent of SPFile.OpenBinaryStream() when all I have is a reference to my entity, without having to fetch the SPFile from the containing SPList by the document's ID first.

Any suggestions?

Thanks

3 Answers 3

2

I am thinking of giving ICustomMapping a go to create a ListItem property on my Entities of type SPListItem and use MapFrom() set it to be the item which it represents. I am just worried about object lifetime/disposal issues, i.e. I'm not sure if the ancestor path of the Item's SPList (SPWeb>SPSite) is still open after the Entity's properties have been populated.

1
  • ah, good point :/
    – James Love
    May 26, 2011 at 18:59
1

There's the SPMetal Extender on CodePlex which might help, but I think you're gonna have to extend the entity further by adding a property to it which returns a Stream, and is effectively a proxy call to the object model.

Of course, as soon as you need to run SPMetal again, you'll loose the custom property.

Then again, you might be able to create an extension method in your own class which will add an OpenBinaryStream proxy call through the entity class... (thinking about it, this is probably the best solution).

3
  • but the entity doesn't seem to hold a reference to the SPListItem it represents, not even internally, so how to get hold of the SPFile to call OpenBinaryStream on it? May 26, 2011 at 16:41
  • You'll have an Id though, from the Item entity?
    – James Love
    May 26, 2011 at 16:53
  • Yes, but inside my entity code I don't have a reference to an open SPWeb, nor an SPList. I would have to open this myself en refetch the item, which I'd rather not do. It feels like an unnecessary second roundtrip. May 26, 2011 at 18:56
1
  1. Get your Web var web = SPContext.Current.Web
  2. Create your file location var location = Path.Combine(entity.Path, entity.Name)
  3. call SPFile file = _web.GetFile(_location)

Easier if you write it as a static extension method for the SPFile class.

1
  • I know you wanted to avoid a "round-trip" but it may be necessary. The extension method will make it more readable though. Feb 24, 2012 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.