The EntityDataSource control is a very powerful one. It allows you to rapidly create database driven application. You don’t have to manually write code for extracting, modification and deleting records from the database. Moreover since this code is backed by Entity Framework, you are not tied up with a particular database schema and can easily change it or even choose other database application.
However when working with EntityDataSource sometimes I feel like I using plain old SqlDataSource and simply have too much unnecessary code in my .aspx files. For instance, you may end up have code like this one:
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=NorthwindEntities" DefaultContainerName="NorthwindEntities" EnableDelete="True" EnableInsert="True" EnableUpdate="True" EntitySetName="Products" Include="Categories, Suppliers" AutoGenerateWhereClause="true"> <WhereParameters> <asp:QueryStringParameter Type="Int32" Name="CategoryID" QueryStringField="CategoryID" /> <asp:QueryStringParameter Type="Int32" Name="SupplierID" QueryStringField="SupplierID" /> </WhereParameters> </asp:EntityDataSource>
That certainly isn’t cool at all. Because it simply shouldn’t be in an .aspx file, not only because it breaks application layers, but simply because it inconvenient. It clutters .aspx files which should be templates only. What if a designer meets code like this? What if accidently change something?
Instead it’s reasonable to move all these lines of code to code-behind.
So, in your .aspx file you just leave this declaration:
<asp:EntityDataSource ID="dsProducts" runat="server" />
While put all the attribute assignments to code-behind:
NorthwindEntities db = new NorthwindEntities(); dsProducts.ConnectionString = db.Connection.ConnectionString; dsProducts.DefaultContainerName = "NorthwindEntities"; dsProducts.EntitySetName = "Products"; dsProducts.Include = "Categories, Suppliers"; dsProducts.EnableUpdate = true; dsProducts.EnableInsert = true; dsProducts.EnableDelete = true; dsProducts.AutoGenerateWhereClause = true; dsProducts.WhereParameters.Add(new QueryStringParameter("CategoryID", TypeCode.Int32, "CategoryID")); dsProducts.WhereParameters.Add(new QueryStringParameter("SupplierD", TypeCode.Int32, "SupplierID"));
In fact, the same technique applies to any other data source control, like LinqDataSource or even ObjectDataSource.