Wednesday, July 8, 2009

DALinq databinding

Databinding in WinForms applications with RemObjects DataAbstract's DALinq is pretty straightforward. For this example I created a standard WinForms DataAbstract project and pointed it to the Northwind database I have in SQL Server. I removed the standard RemoteDataAdapter and replaced it with the LinqRemoteDataAdapter from the Visual Studio 2008 toolbox. I then clicked on the LinqRemoteDataAdapter's Smart Tag so I could create my LINQ classes:



In this exercise I'll create two buttons. One to open the query and one to update any changes I make to a field. The code for the query will be similar to the code I used in a previous blog post, but not quite the same. We'll come back to that later.


private void btnOpenQuery_Click(object sender, EventArgs e)
{
_list = from cust in linqRemoteDataAdapter.GetTable<Customers>()
where (cust.City == "México D.F.")
orderby cust.CompanyName ascending
select cust;

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = null;
dataGridView1.DataSource = _list.ToDABindingList();
}

And the code that we'll run after changing a field in the grid is equally straightforward:


private void btnUpdate_Click(object sender, EventArgs e)
{
((DABindingList<Customers>)dataGridView1.DataSource).SaveChanges(linqRemoteDataAdapter);
linqRemoteDataAdapter.ApplyChanges();
}

Easy! the only problem I had was I originally only selected a few fields from the table. That query would have been written like this:


_list = from cust in linqRemoteDataAdapter.GetTable()
where (cust.City == "México D.F.")
orderby cust.CompanyName ascending
select new { cust.CustomerID, cust.ContactName, cust.Address, cust.City };

As you can see I used a parameterized select statement to get just the fields I wanted from the table. Unfortunately to use the _list.ToDABindingList(); method you must have a parameterless select statement. That means all the fields are brought over. This isn't as efficient in a WinForms application using the standard DataAbstract RemoteDataAdapter and DataSets. That method is much more efficient because you have complete control over what fields are brought across the wire. It will also only update the change deltas for the updates for your updates. I've asked support if there's any way around this, or if they plan on adding the option to use parameterized select statements in the future. If they do, then DALinq databinding would be just as nice to use as the standard RemoteDataAdapter using DataSets.


About The Author

Ron Grove draws on over ten years of training, network administration and development experience. He loves to work with new technology and see how that technology can be best utilized by his clients. You can find him through his company Evanoah, LLC and his LinkedIn profile is here.

0 comments:

Post a Comment