Setting the Context for Using the BDC Object Models
Last modified: April 15, 2010
Applies to: SharePoint Server 2010
To use the Microsoft Business Connectivity Services (BCS) object models with a deployment of Microsoft SharePoint Foundation, Microsoft SharePoint Server, or Microsoft Office 2010, your code must first get a reference to the objects it will be working with, including Web sites, BDC Shared Service, Metadata Catalog, and BDC Remote Offline Runtime. There are two ways for doing this: one applies when your code will be used in a console or Windows-based application; the other applies when your code will be used in a browser-hosted application, such as when you choose "Web Site" as the type of Microsoft Visual Studio project.
Most sample code in the Business Connectivity Services Object Model Code Snippets section of the SDK uses the second way, so if you are writing for a browser-based application, you must change the code. The following sections provide guidance for using the Business Connectivity Services object models.
To work with the BDC by means of a browser-hosted application, your code must first establish the context to the BDC Shared Service that should handle the requests that are made to the BDC.
You must obtain the HTTP context of the BDC Shared Service in the code. We recommend that you do this by using the Microsoft.SharePoint.SPServiceContext class and its members.
To return the current shared service used by a site, you can use the SPServiceContext.Current property after you have established the site context.
The SPServiceContext.Current property must be set up explicitly in a console or Windows-based application if you are using the DatabaseBasedMetadataCatalog object. BDC assumes that there is an SPServiceContext.Current property established by any callers to it so that it can appropriately call other services such as User Profile or Secure Store Service internally. If you are writing code for either type of application and you want to work with a specific site collection, use the SPSite constructor to instantiate an object that represents the site collection.
Your code should dispose any SPSite or SPWeb object obtained by using a constructor. There are a number of nuances to the best practices with regard to when SharePoint Foundation objects should and should not be disposed. For information, see Disposing Objects.