我正在使用本地数据库来存储我的数据。我有*.sdf
从中加载的文件Isolated Storage
,因为我希望我的应用程序也可以在离线模式下工作,所以如果用户不想要,他不必更新数据。
这就是我的DataContext
样子:
public class TablesDataContext : DataContext
{
// Specify the connection string as a static, used in main page and app.xaml.
public static string DBConnectionString = "Data Source=isostore:/MyDatabase.sdf";
// Pass the connection string to the base class.
public TablesDataContext(string connectionString)
: base(connectionString)
{ }
// Specify a single table for the items.
public Table<CustomerItem> CustomersTable;
public Table<ProductItem> ProductsTable;
}
如果需要,我在这里App.xaml.cs
创建我的数据库:
// Create the database if it does not exist.
using (TablesDataContext db = new TablesDataContext(TablesDataContext.DBConnectionString))
{
if (db.DatabaseExists() == false)
{
//Create the database
db.CreateDatabase();
}
}
dataContext = new UserDataContext();
我SettingsPage
在其中更新所需信息:
public partial class SettingsPage : PhoneApplicationPage
{
// Data context for the local database
private TablesDataContext tablesDB;
// Define an observable collection property that controls can bind to.
private ObservableCollection<CustomerItem> _customersTable;
public ObservableCollection<CustomerItem> CustomersTable
{
get
{
return _customersTable;
}
set
{
if (_customersTable != value)
{
_customersTable = value;
NotifyPropertyChanged("CustomersTable");
}
}
}
// Define an observable collection property that controls can bind to.
private ObservableCollection<ProductItem> _productTable;
public ObservableCollection<ProductItem> ProductTable
{
get
{
return _productTable;
}
set
{
if (_productTable != value)
{
_productTable = value;
NotifyPropertyChanged("ProductTable");
}
}
}
public void addingCustomersToDatabase(List<CustomerJSON> customersList)
{
// Define the query to gather all of the to-do items.
var customersTablesInDB = from CustomerItem todo in tablesDB.CustomersTable
select todo;
// Execute the query and place the results into a collection.
CustomersTable = new ObservableCollection<CustomerItem>(customersTablesInDB);
tablesDB.CustomersTable.DeleteAllOnSubmit(CustomersTable);
tablesDB.SubmitChanges();
foreach (CustomerJSON customer in customersList)
{
// Create a new to-do item based on the text box.
CustomerItem newCustomer = new CustomerItem
{
// Filling customer data from JSON object
};
// Add a to-do item to the observable collection.
CustomersTable.Add(newCustomer);
// Add a to-do item to the local database.
tablesDB.CustomersTable.InsertOnSubmit(newCustomer);
tablesDB.SubmitChanges();
}
}
public void addingProductsToDatabase(List<ProductJSON> ProductsList)
{
// Same things as in previouse method but with products objects
}
private void Load_Click(object sender, RoutedEventArgs e)
{
addingCustomersToDatabase(customersList);
addingProductsToDatabase(productsList);
}
}
更新信息后,我确定数据是最新的,但只有在我关闭我的应用程序之前。如果我重新打开应用程序,它仍然有旧数据。如果我理解正确,它不应该已经保存在我的*.sdf
文件中吗?顺便说一句,我正在使用 Linq。
编辑:
我设法检查它,我发现在 JSON 解析之后,数据库立即更新(*.sdf 文件充满了新数据),但是当我再次关闭并打开应用程序时(不是构建,只是在模拟器上重新打开),它再次具有旧数据。