If you're using databound controls (e.g. FormView) and binding them to an EntityDataSource you might want to be able to modify (and save) the underlying entity from code. For example, if you have a Question entity bound to a FormView via an EntityDataSource you might want a button to allow the use to vote up or down the question (like StackOverflow for example). To be able to do this without extra trips to the database, the first thing we need to do is get hold of the EF ObjectContext that the EntityDataSource is using.
// Context that we can use for code-behind operations
ObjectContext questionObjectContext = null;
protected void QuestionEntityDataSource_ContextCreated(object sender, EntityDataSourceContextCreatedEventArgs e)
questionObjectContext = e.Context;
When the QuestionEntityDataSource creates it's context, we take a reference to it in our private field questionObjectContext.
Now in the button click we can up-vote the question:
protected void btnVoteUp_Click(object sender, EventArgs e)
// force a databind to ensure we have a DataItem in the FormView
// Get the actual entity represented by the FormView
Question questionToUpdate = FormView1.DataItem.WrappedEntity<Question>();
// using our 'copy' of the EntityDataSource ObjectContext, save the changes
// Force rebind of FormView to ensure newest data displayed
If using ASP.NET EntityDataSource and databound controls you may need to access the actual entity object being represented in the control, e.g. a data row in a table or a single entity in a FormView. The actual entity is not readily available however as it is automatically wrapped in a System.Web.UI.WebControls.EntityDataSourceWrapper which is not accessible. The extension method below allows you to gain access to the strongly typed, underlying entity. It is based on the article by Diego Vega which explains the wrapping behaviour in more detail.
/// Gets the actual EF entity object that is being wrapped and databound.
/// Advert ad = myFormView.DataItem.WrappedEntity<Advert>();
/// (where myFormView is databound to EntityDataSource returning Advert entity)
static class WrappedEFEntityExtensions
public static TEntity WrappedEntity<TEntity>(this object dataItem) where TEntity : class
var entity = dataItem as TEntity;
if (entity != null)
var typeDescriptor = dataItem as ICustomTypeDescriptor;
if (typeDescriptor != null)