CodeFluent Entities and ASP.NET Web Forms Binding: Inserting Data
In the previous posts we’ve seen how to display data declaratively using the generated code, so in this post we’ll illustrate how to insert data declaratively using ASP.NET Web Forms.
The first step is to configure your ObjectDataSource control to support inserts and updates, such as:
<asp:ObjectDataSource runat="server" ID="ContactDataSource" TypeName="ContactAdmin.Contact" DataObjectTypeName="ContactAdmin.Contact" SelectMethod="LoadByEntityKey" InsertMethod="Insert"> <SelectParameters> <asp:QueryStringParameter Name="key" QueryStringField="key" DefaultValue="-1" /> </SelectParameters> </asp:ObjectDataSource>
Note: We’re using the ‘LoadByEntityKey’ method as the select method instead of the ‘Load’ method to avoid a cast and support composite keys.
Now that we have a data source, we need to setup a control which will allow us to create or edit an instance of an entity. ASP.NET Web Forms provide several controls to do so including the DetailsView and FormView controls. In practice, they are almost the same, the main difference being that the DetailsView control uses a tabular layout where each field of the record is displayed as a row of its own where as the FormView uses a template which you can define yourself. For simplicity’s sake, we’ll use a DetailsView in this example which is defined as so:
<asp:DetailsView runat="server" DataSourceID="ContactDataSource" DefaultMode="Edit" DataKeyNames="Id, RowVersion"> <Fields> <asp:BoundField HeaderText="First Name" DataField="FirstName" /> <asp:BoundField HeaderText="Last Name" DataField="LastName" /> <asp:ButtonField CommandName="Insert" Text="Insert" ButtonType="Button" /> </Fields> </asp:DetailsView>
Note: You must set the DataKeyNames property for the automatic updating, deleting, and inserting features of the DetailsView and FormView controls to work.
And here it is you now have an insert form to create a new contact: