Digging into LinQDataSource

The sample code that ScottGu showed for LinQDataSource made it look like it should be called LinQToSqlDataSource.

After installing Beta2 I took a look at it.

It only has design time support for LinQ To SQL, but you can bind it to any LinQ query in the _Selecting event:

protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    e.Result = from c in MyCustomer.GetCustomers() select new { c.Name };
}

I did not find a way to handle insert/update/delete, so it looks that any third party O/R mapper will need to implement its own DataSource to handle it. However, in the LinqDataSourceView, there are some implementation details that make me hope they fix that. They have protected virtual methods with the following signature:

protected virtual void UpdateDataObject(object dataContext, object table, object oldDataObject, object newDataObject)

Note that the 'dataContext' is 'object', so if you have other datacontext type that it's not LinQToSQL's one, you could access it from there. In order to try that, I needed to replace the DataSourceView that theLinqDataSource control uses, so I subclassed LinQDataSource so the GetView(string) returned my instance, but it did not work, as the LinQDataSource internally asks for the view to another method that is not virtual.

Other interesting stuff I found digging with Reflector:

  • The DataSource only returns one view, so if you have a control that can bind to hierarchical structures, you will not have a good design time experience with LinqDataSource, as the control can't know the structure of the nested views. The same happened with the DataSource controls that shipped in ASP.NET 2.0, but in some of them it did not make sense (like the SqlDataSource) but in others did and it was not supported (XmlDataSource).
  • The LinqDataSource supports specifying a where clause, like

                 Where="Name.CompareTo(@TextValue)>0"

to do this, they should have a framework to create a LinQ query from a string. As I implemented pretty limited one sometime ago, I was eager to see how they did. There is an internal  System.Web.UI.WebControls.DynamicQueryableWrapper class that does exactly that. I thought it would be a good idea to make it public, but today I found this Building LINQ Queries at Runtime in C# article that looks like a much better solution. I need to take a deeper look at it.

No Comments