SQLite loses data (insert, update) after restarting app - c#

When I update my data:
using (SQLiteConnection conn = new SQLiteConnection(DB_PATH))
{
var query = conn.Table<kursy>().Where(k => k.kurs == kursStaryRubel).SingleOrDefault();
query.data = kursAktualnyData;
query.kurs = kursAktualnyRubel;
conn.Update(query);
}
Everything works fine. The data is updated. But when I close and open my application again, this data has old value - it's not updated. I'm using the same database, it is not recreated. Why is it happening?
My DB_PATH:
public static string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "test.db");
My database file has property Copy to Output Directory set to Copy if Newer

I've solved the problem.
Unconsciously database was replaced at the start. The problem was that I created database in the Storage , not in the IsolatedStorage. I do not know if I understand this correct, but when it was created in Storage, the database was created in the memory of the application, and that's why database expires when I close app. But when I create database in IsolatedStorage it is permanently placed in the phone memory. And then even if I turn off the application, the database remained, because it was created in the phone memory, not in the application memory.

Related

Linq to SQL not saving to database on SubmitChanges()

I have a database with three tables in it. I created all the tables within Visual Studio. My C# code is connecting to the database using Linq to SQL. The table I am having problems with is not updating on SubmitChanges().
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
tbl_Inventoryv2 inv = new tbl_Inventoryv2();
inv.Title = addTitleTextBox.Text;
inv.Model = addModelTextBox.Text;
inv.Category = addCategoryTextBox.Text;
inv.Quantity = int.Parse(addQuantityTextBox.Text);
inv.Price = decimal.Parse(addPriceTextBox.Text);
inv.Description = addDescriptionTextBox.Text;
db.tbl_Inventoryv2s.InsertOnSubmit(inv);
db.SubmitChanges();
int id = inv.IdInventory;
MessageBox.Show($"Item creation successful. Item number is {id}");
}
My database does have a primary key called IdInventory that is set to increment. Within the program, the correct increments are working as shown in my MessageBox statement above, but it never actually gets saved to the database. I have also checked the properties of the database file in Visual Studio and the path to the database is correct, as well as the Copy to Output Directory is set to Copy if Newer. Most of the questions I have looked up indicate that is usually the problem, but that doesn't look like the case for me. I am new to SQL and interacting with it via Visual Studio/c#, and SQL in general, so any input is greatly appreciated.

TableAdapter.Update(dataset) not saving to database in Ado.NET

I have seen the other posts on this subject. Yet so far there has been no solution. I am working with Visual Studio 2013 in C#.
I have a database "Database1.mdf" with one table called Customers, which just has two records. I created the DataSet named CustomersDataSet (Menu: Project, Add New Data Source...) based upon this database.
This is my code.
CustomersDataSetTableAdapters.CustomersTableAdapter cta = new CustomersDataSetTableAdapters.CustomersTableAdapter();
CustomersDataSet ds = new CustomersDataSet();
// Fill our customersDataSetTable with the data from customers adapter
cta.Fill(ds.Customers);
Console.WriteLine("BEFORE");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
Console.WriteLine("\nMaking changes now...");
// Insert a new record
CustomersDataSet.CustomersRow newCustomer = ds.Customers.NewCustomersRow();
newCustomer.FirstName = "Brian";
newCustomer.LastName = "Faley";
newCustomer.City = "Denver";
newCustomer.State = "CO";
ds.Customers.AddCustomersRow(newCustomer);
// Update a record, [0] = gets access to the first row of the customers table
ds.Customers[0].FirstName = "Robert";
// Delete a record
ds.Customers[1].Delete();
// Update the dataset ds. Commit changes to the database
cta.Update(ds);
Console.WriteLine("\nAFTER");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
It works insofar as I do see the changes made to the dataset after "AFTER".
Yet I can run it as often as I wish - never are the changes written to the underlying database. The Update should do just that, but it does not. There is no AcceptChanges() in my code. I have followed up on all these suggestions - they do not lead anywhere.
Would someone have an idea?
I googled far and wide and all posts on this issue are unsolved.
When you debug the application the mdf file is copied to the bin\debug folder and your changes are committed to the database there.
Every time you start the project the mdf in the debug folder gets overwritten with the original database.
You can stop this behavior by going to the database settings in your solution and set the database to copy only if your version is newer.
Chances are your code was working all along.
Hope this helps.

MS Access database not up to date? (VS Web Developer Studio)

I'm taking a class in C# web dev and I'm currently trying to display data from a .mdb (Microsoft Access) database. I have two pages that both want to show a table stored in the database in a grid view. One page's form uses function that connects the the db and then writes to the table to the grid. it connects with this call:
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
sqlDA = new OleDbDataAdapter("select * from tblPersonnel where LastName = '"+strSearch+"'", sqlConn);
//Initialize a new activity
DS = new dsPersonnel();
//Add rows to the dataset from the data source
sqlDA.Fill(DS.tblPersonnel);
The database is called PayrollSystem_DB.mdb. In the other page I placed a SqlDataSource control on the page and connected it to PayrollSystem_DB.mdb. Then set this to the gridView. However when running, the the first page shows a long table with data I've entered since last week. and the 2nd page shows only data from the first day I tested it. Looking at the db in the vs explorer the tables are identical to teh second page.
So I'm wondering were all the other data is being stored that the first page is showing? Am I unknowingly using a database I can't see in the solution?
Just a guess, but have you tried clearing your browsers cache and then looking at the first page again? Try that. If the data is still showing I would compare the size of the MDB before and after an insert to see if the MDB grows. If not, try a search of all the files on your PC limiting it to only files modified recently, I think that will at least help you find where the data is being stored.

How to add entity-framework to console application (images are included)

I try to add entity-framework to console application:
I press "add new item" and
then
then
then I added code:
class Program
{
static void Main(string[] args)
{
try
{
Database1Entities db = new Database1Entities();
db.AddToTableTest(new TableTest { name = "name" });
db.SaveChanges();
int count = db.TableTest.Count();
int ui = 9 + 0;
}
catch (Exception e)
{
}
}
}
It gives no error, but I don't see any changes in database.
I described the issue better here
I did the same steps you did to setup a EF model. your database.mdf file has the Copy to Output Directory set to Copy always, that means that every time you hit F5 (build or debug your app) the file is getting replaced by the empty one on your project.
Changing the Copy to Output Directory on the Properties window of the mdf file should solve your problem.
If you use Copy if newer you are going to be persisting any modifications on the contents of the database until you edit the database (mdf) itself.
With Do not copy any change to the mdf file is not going to get reflected on your application and will probably generate problems with EF.
I recommend for this scenario that you use Copy if newer and fill your basic data in the mdf file so you will have it always available.

Creating Sqlite Embedded database from application

I have a winforms app that uses sqlite to store data. Instead of shipping a blank database, can I use scripts to create the tables the first time the user uses the app? Can you point to a C# example?
Update: I want to avoid shipping a blank database. So if a user install the app for 1 user only, only his profile gets a copy. All users profile gets the database if the install is for all users.
Yes, this is possible:
When the application first runs, check if the database file exists.
If it doesn’t, open it with the Sqlite option FailIfMissing=False. This will create a new file.
Then, use SQL commands like CREATE TABLE ... to create the schema structure.
For the second step, I use code that looks something like this:
public DbConnection CreateConnectionForSchemaCreation(string fileName)
{
var conn = new SQLiteConnection();
conn.ConnectionString = new DbConnectionStringBuilder()
{
{"Data Source", fileName},
{"Version", "3"},
{"FailIfMissing", "False"},
}.ConnectionString;
conn.Open();
return conn;
}

Categories