Reputation: 32499
I have Data = new ObservableCollection<DATA>(dataContext.DATA);
dataContext
is my Entities. DATA
is SQL Server table.
Now I run Import method, which fills DATA
table on SQL Server:
public static void Import(DataTable table)
{
var dataContext = DataContext.Instance.Entities;
foreach (DataRow row in table.Rows)
{
.......
var dataRow = new DATA
{
.........
};
dataContext.AddToDATA(dataRow);
}
dataContext.SaveChanges();
}
But my ObservableCollection Data
is still empty. How do I update it?
Upvotes: 1
Views: 753
Reputation: 32515
ObservableCollection<T> Constructor (IEnumerable<T>)
:
Initializes a new instance of the ObservableCollection class that contains elements copied from the specified collection.
The keyword here is that it copies the element from the collection. After that it does not retain any synchronization with the enumeration that you passed in. Your code is updating the dataContext
object, not your Data
object (The ObservableCollection). You will either have to build out your own synchronized version of ObservableCollection or create methods to keep them in sync.
If you aren't concerned with keeping the dataContext
object synchronized and only wanted to use it in the one-time load, then you have to have all the appropriate objects in that enumeration before using it in the constructor of your ObservableCollection.
My guess is you do something similar to the following:
Data = new ObservableCollection<DATA>(dataContext.DATA)
// Afterwards...
Import(foobar);
It should be:
Import(foobar);
// Afterwards...
Data = new ObservableCollection<DATA>(dataContext.DATA)
Upvotes: 3
Reputation: 33833
You need to reget the data from the datacontext and add it to the observable collection at that point.
public static void Import(DataTable table)
{
var dataContext = DataContext.Instance.Entities;
foreach (DataRow row in table.Rows)
{
.......
var dataRow = new DATA
{
.........
};
dataContext.AddToDATA(dataRow);
}
dataContext.SaveChanges();
var data = datContext.whateverretreval();
Data = data;
}
Upvotes: 1