views:

28

answers:

1

Hi, apologies in advance for the noob question, I've only been using WPF for a few weeks and SQL Server for a few days, but I can't find out how to do this anywhere on the web so far.

I have a database on SQL Server with one table in it 'User', and have an application that can display data (Username) from that table in a ListView using Bindings which works fine.

However, if the database has items added/deleted etc by something other than the application, the changes are not automatically reflected in the ListView. I thought Bindings would take care of this, but maybe that's only if the application itself modifies the data?

XAML:

<Window.Resources>
    <DataTemplate x:Key="ShowUser" DataType="{x:Type db:User}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Username}" />
        </StackPanel>              
    </DataTemplate>
</Window.Resources>
...
    <ListView Grid.Row="2" x:Name="TheListView" ItemTemplate="{StaticResource ShowUser}">            

Code behind:

    public MainWindow()
    {
        InitializeComponent();

        MyDBEntities db = new MyDBEntities();
        var users = from u in db.Users
                    select u;

        IListSource query = (IListSource)users;
        TheListView.ItemsSource = query.GetList();
    }

What do I need to do to get the ListView dynamically updating when the database contents are changed by something other than the application itself?

Thanks in advance, Daniel

A: 

This is the drawback of directly accessing the database in a two-tier application.

One crude solution is to poll the database for changes. I am not sure of EF syntax, but there is probably some way to 'refresh' a query.

SQL server has a few facilities to notify you about changes, but in reality its probably not a great idea to build a back end so closely coupled to the database.

If you added a third tier, it would be easy to intercept when someone makes a change to the data (before it is sent to the db), at which point you cant send a copy of the changes to all the client. In this architecture its often best to think of the db as simply a "dumb" persistence mechanism behind your middle tier (where all the clever stuff happens).

As for actual implementation details I wish I could say there is good news. Most of these solutions get very difficult very quickly once you start to think about concurrency.

Schneider
Ahh, I was hoping there was some clever way to use ObservableCollection or something that would magically know when the data had changed. Alas it is not that easy!Your 3 tiered design makes a lot of sense (but sounds like a lot of work - eep!). So I'd need to make some kind of server application that talks to the database, and the client apps talk to the server app?Cool, thanks for putting me on the right track!
Daniel
We all wish there was such a clever way :)
Schneider