I was developing an application using Entity Framework and storing data in a .mdf database. My code can read the data, apparently it can save too, but only apparently. It get no erros, while the program is running it act like the data was saved, I can for example save an object, dispose the context, create a new one, and then when I search my object it's there! But when I query the database to see the stored data there's nothing there. If I close the app and run it again, all data is gone. Here's a example code I wrote just to test:
using (DatabaseEntities e = new DatabaseEntities())
{
for (int i = 0; i < 50; i++)
{
User u = new User();
u.Nome = "User" + i.ToString();
e.AddToUser(u);
}
int c = e.SaveChanges(true);
List<User> us = e.User.Where<User>(x => x.ID < 50).ToList<User>();
foreach (User u in us)
Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome);
Console.ReadKey();
}
When I run this I get the 50 outputs, if I look the content of the c variable in the debug, there's 50 changes, everythings seems to be fine, but when I start my query browser and look in the content of my MDF database, there's nothing there.
Probably it's something very simple but I can't see what it is, I need your help.
I just found what was going wrong, and I guess there's nothing wrong actually. I forced an error, and then I could see the database that I was accessing was in the bin directory, the Visual Studio copied my database to the bin directory everytime I run the app, so that's why if I add some data manually I could see it, but the saves in the runtime aren't persisted. I always worked with database in servers, it's my first time with local databases, so I messed up it, but thankz a lot for the help!
If you wish to disable copying the database on build, then you have to acces the Copy to Output Directoy
from the .mdf
file from your Solution Explorer.
Simply change it to Copy if newer
or Do not copy
.
Be aware that Copy if newer
holds some risks when accesing a .mdf
Database.
A few things leap to mind:
Also - I don't think it'll matter in this case, but to verify data you should use a different entities/data-context:
using (DatabaseEntities e = new DatabaseEntities()) {
for (int i = 0; i < 50; i++) {
User u = new User();
u.Nome = "User" + i.ToString();
e.AddToUser(u);
}
int c = e.SaveChanges(true);
}
using (DatabaseEntities e = new DatabaseEntities()) {
List<User> us = e.User.Where<User>(x => x.ID < 50).ToList<User>();
foreach (User u in us)
Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome);
}
Console.ReadKey();
Like I said - I doubt it'll matter here, but worth checking...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With