views:

113

answers:

1

Hello! I'm using the Entity Framework classes to make changes to my database like this:

testEntities.Products.AddObject(product);

I've got a ListBox bound to testEntities.Products and it shows them correctly, but when I add a new object and I save the changes (testEntities.SaveChanges()), the product appears into the database, but the ListBox isn't updated.

I really would like that those object collections from the EF would be "observable". Is there a simple way to achieve this?

Thanks a lot!

(I'm using VS.NET 2010)

A: 

Just a step away. Try not to use declarative DataSource, but a query instead.
In this case you have better flexibility and full control over the data binding process. Here is a small sample:

    private void Form1_Load (object sender, EventArgs e) {
      listBox1.DataSource = context.MASTER.Select(m => m.DATA);
    }

    private void button1_Click (object sender, EventArgs e) {
      context.AddToMASTER(new MASTER
      {
        ID = 5,
        DATA = "5"
      });
      context.SaveChanges();
      listBox1.DataSource = context.MASTER.Select(m => m.DATA);
    }

You can also put the code of the query into a separate RefreshList method, and simply call this method when you need to refresh the list in the code. That will be convenient also if you have a set of these list boxes and other databound controls.

Devart
Thanks! I will try it. By the way, is there some breaking change in .NET Framework 4.0 to do this? I ask you this because I've seen you use context.AddToX instead of entities.X.AddObject(). The first one is obsolete, I think (the contextual help told me it is).
SuperJMN
You can use context.MASTER.AddObject instead of context.AddToMASTER, it is a EF v4 approach.
Devart
Is that the best we can do? I mean, isn't there a declarative way?
SuperJMN
Hello? is there somebody?
SuperJMN
Unfortunately, we are not aware of any declarative way.
Devart