简体   繁体   中英

How do I store data from an ObservableCollection into an SQL database?

I have some records inside an ObservableCollection.

void proxy_AddPayNowOrderCompleted(object sender, AddPayNowOrderCompletedEventArgs e)
{
    listBox1.ItemsSource = e.Result;
    ObservableCollection<Product> Products = this.listBox1.ItemsSource as ObservableCollection<Product>;
}

My Product entity will have prodid, prodname, prodrice. There will be many of these entities inside the ObservableCollection. I want to save all the records in the ObservableCollection into my SQL database. I'm using this code to save one record into the database.

private void btn1_Click(object sender, RoutedEventArgs e)
{
    proxy.AddPayNowOrderCompleted += new EventHandler<AddPayNowOrderCompletedEventArgs>(proxy_AddPayNowOrderCompleted);
    proxy.AddPayNowOrderAsync(orderdate, prodid, orderprodname, orderprice, orderstatus, custemail, paymentdate);
}

How can I store all of the records inside the ObservableCollection and insert them into the database?

Something like this should work:

ObservableCollection<Product> Products = this.listBox1.ItemsSource as ObservableCollection<Product>;
proxy.AddPayNowOrderCompleted += new EventHandler<AddPayNowOrderCompletedEventArgs>(proxy_AddPayNowOrderCompleted);
foreach (Product p in Products)
{
    proxy.AddPayNowOrderAsync(p.orderdate, p.prodid, p.orderprodname, p.orderprice, p.orderstatus, p.custemail, p.paymentdate);
}

Your service may have a method that allows you to pass in multiple products at once, which would be much more efficient than making all those separate round trips, but without more information about the members in your proxy class, that's impossible to determine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM