C# - SaveChanges() doesn't update the database - c#

I tried many solutions found on Stackoverflow but none worked. I have a local database linked with EF Designer.
I'm using Entity Framework to create rows and store them into the database. It's working since database.SaveChanges(); returns 1 (not zero). Then I loop on the database rows and I can see that data were well saved.
Nonetheless, when I'm closing my console app and refreshing database, I can't find the values I just added and the rows I generated.
Working on this issue since few hours, browsed Internet but none of the answers helped me.
I already tried to do database.User.Attach() and EntityState.Modified but they didn't work.
I even tried to move my code in a different class, but it didn't work.
public static void AddClient(String firstName, String lastName, int phoneNumber, String email, String wishlist)
{
using (DatabaseEntity database = new DatabaseEntity())
{
database.User.Add(new User() {
First_Name = firstName,
Last_Name = lastName,
Phone_Number = phoneNumber,
Email = email,
Wishlist = wishlist
});
database.SaveChanges();
}
}
I expected data to be saved in the database after closing app, but they aren't.

I found the solution.
When Visual Studio uses local databases, at each debug it copies the databases and works on the copied.
So, I had to add a new connection on the Server Explorer that was targetting my_project_path/bin/debug/database.mdf
Then, I had to edit one of its properties which was Copy to Output Directory. Its new value is now Copy if Newer and now my datas are well saved in the database.

Related

SQLite C# / Insert Command adds no data into the database

I've got a problem resolving my SQLite Database issue.
As the title says, I'm "simply" trying to add some data into a particular table of the database file using SQLite - with the Microsoft.Data.SQLite package.
The code is executed without any errors and even the SQL-Statement execution returns that one row altered. But when I take a look into the db with the db-browser the "inserted" row, simply isn't there at all. This is the code executed:
SqliteConnectionStringBuilder _sqlconsb = new SqliteConnectionStringBuilder();
_sqlconsb.DataSource = _SqliteDatabase;
_sqlconsb.Mode = SqliteOpenMode.ReadWrite;
SqliteConnection _sqlconn = new SqliteConnection(_sqlconsb.ConnectionString);
_sqlconn.Open();
SqliteCommand _sqlcmd = _sqlconn.CreateCommand();
_sqlcmd.CommandText = #"INSERT INTO Mediatypes (Name, Type) VALUES ('Hurrey-1', 'i')";
int _numInsert = _sqlcmd.ExecuteNonQuery();
_sqlconn.Close();
return _numInsert;
I created a complete new WPF-Application with some buttons and executed the same piece of code in that new app. There it also executes without any issues and the data is indeed added to the db file, which I again checked with the db browser.
I've got no idea, with this particular code adds the new row of data in the test app, but does'nt do it's job in my app. I'm also complete lost in further debbuging this issue, because it's executed without any issues.
One more point to consider, I've other methods in my app which are able to add data successfully to the database into other tables. So i think it sholdn't be the database file itself nor the MS.Data.SQLite package in my solution.
I hope there's anyone out there who's able to point me into the right direction to get this debbuged and or solved ...!

Entity Framework not inserting record

I'm working on a small project in WPF where you can insert, edit and search Recipes. I'm using Entity for this.
Recipe has a property, list<Ingredient>. When I insert an ingredient, it's OK, but when I insert a recipe with a list<Ingredient>, everything is ok except that in table recipe, there is no column ingredient at all. But in debug I clearly can see that in my method where I insert a recipe , the object recipe has ingredients count... I have spend couple hours trying different things out but with no luck.
This is how I insert (same as ingredient , where everything works)
public static void InsertRecipe(Recipe recipe)
{
RecipeDbContext ctx = new RecipeDbContext();
ctx.Recipes.Add(recipe);
ctx.SaveChanges();
}
Screen-shots from debug:
Recipe Table
Recipe object properties
Just for testing purposes , the ingredients should come from a listbox later on.
When I press ctrl property menu is fading away (reason why screen-shot is the way it is)
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. RecipeDataBase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=RecipeDataBase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
First, you must insert Recipe item and get the ID :
public static int InsertRecipe(Recipe recipe)
{
RecipeDbContext ctx = new RecipeDbContext();
ctx.Recipes.Add(recipe);
ctx.SaveChanges();
return recipe.recipeID;
}
And after that you can insert all Ingrédients, Something like that
public static void InsertIngredient(List<Ingredient> Ingredients, int recipeID)
{
IngredientDbContext ctx = new IngredientDbContext();
foreach (var ingredient in Ingredients)
{
Ingredient newItem = new Ingredient { IngredientID = ingredient.Ingredient,..., recipeID = recipeID};
ctx.Ingredient.Add(newItem);
}
ctx.SaveChanges();
}

Ado.net firebird commit insert new lines to table

I'm adding new lines to a database for our company's "order list" for each order created, using the firebird ado.net client. The code i've written works fine for listing items, but inserting new ones doesn't appear elsewhere (e.g. in flamerobin). What I think is happening is that the transaction isn't being committed, seeing as it's recognised within my code (can't add duplicate values).
Code:
using (FbConnection fbCon = new FbConnection)
{
fbCon.Open();
***command w/ parameterised command string***
using (FbTransaction fbTrans = fbCon.BeginTransaction())
using FbCommand orderCommand = new FbCommand(cmdString, fbCon, fbTrans)
{
***Adding parameters and values***
try
{
int recordsAffected = orderCommand.ExecuteNonQuery();
fbTrans.Commit();
}
catch (FbException E)
{
fbTrans.Rollback();
fbCon.Close();
throw E
}
}
recordsAffected returns 1 but I am not able to see the updated values in flamerobin or the db management program. Am i missing something?
If anyone else runs into this problem, it's in Visual Studio's debugging settings. https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx explains pretty clearly, but basically VS makes a copy of your database in bin/Debug of your project (Ostensibly to not mess with your data) but if you actually need to use/view the data externally, either link your external application to the debug database (e.g. flamerobin). You may also need to set your project database settings to Copy if Newer if you want your updates to stay, as the default setting copies the database into the folder each time you run your c# app.

Howto to access the tables of an attached database?

I am using sqlite-winrt on a Windows Phone 8 project to work with SQLite databases. Works quite will, except a problem with attached databases:
There are two identical database (same tables, different content) A and B. B is attached to A:
database dbA = new Database(dbAFile);
await dbA.OpenAsync();
await dbA.ExecuteStatementAsync("ATTACH B.sqlite AS AttachDB");
query = "SELECT * FROM SomeTable";
using (Statement sqlStatement = await dbA.PrepareStatementAsync(query)) {
while (await sqlStatement.StepAsync()) {
...List Content of SomeTable in Table A --> No Problem
}
}
query = "SELECT * FROM AttachDB.SomeTable";
using (Statement sqlStatement = await dbA.PrepareStatementAsync(query)) {
while (await sqlStatement.StepAsync()) {
...List Content of SomeTable in Table B --> Crash in PrepareStatementAsync
}
}
When using to access the Table "SomeTable" in the attached database an Exception is thrown when preparing the statment. The Exception does not show the source of the problem but I managed to get the SQL error message, which is:
"no such table: AttachDB.SomeTable"
Of course database B has a Table "SomeTable". When I connect to this database directly I can access table "SomeTable" without any problem.
I thought that I could be a problem that B has exactly the same tables as A and create a table "OnlyInB" in B. But accessing AttachDB.OnlyInB also fails. According to the sqlite doc one can skip the database name when the table name is unique. Thus "OnlyInB" should work as well. But is does not. "SELECT * FROM OnlyInB" shows "no such table: OnlyInB"
I testes the same scenation with the "SQLite Manager" Extension of Firefox (opened A, attached, B...) Selecting Data from AttachDB.SomeTable or any other table in B is not problem there. The Problem only occurs when using sqlite-winrt.
I also tested if there could be any problem with attaching B to A. But there isn't. When I try to attach B twice or to attach a third database using "AttachDB" again an error is shown that clearly states that B is correctly attached to A. The attaching seems to work perfect, except the problem that I cannot access any tables in B...
Any advise?
Thank you very much!
This statement:
ATTACH B.sqlite AS AttachDB
is not valid SQL; the file name must be a string.
In any case, you should always include the full path to the database file; otherwise, SQLite will open the database in the current path, and, if the file does not exist, try to create a new, empty database:
ATTACH '/some/where/B.sqlite' AS AttachDB

Cannot save to database or retrieve (right info) from it

I am saving data to the database "successfully", using:
try
{
// Save the new Client now.
Profile profile = new Profile()
{
Salutation = Salutation,
FirstName = FirstName,
MiddleName = MiddleName,
LastName = LastName,
Gender = Gender,
DateOfBirth = DateOfBirth,
CompanyName = ClientCompanyName,
StreetAddress = StreetAddress,
Suburb = Suburb,
PostCode = PostCode,
State = State,
Country = Country,
ABN = ABN.ToString(),
ACN = ACN.ToString(),
TelephoneNumber = TelephoneNumber,
MobileNumber = MobileNumber,
EmailAddress = EmailAddress
};
database.Profiles.Add(profile);
database.SaveChanges();
Console.WriteLine("Client saved.");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message + Environment.NewLine + exception.InnerException);
}
and it says it's been saved. But when I look in the database - nothing's there!
And, when I try to get the first name of the person I just added, it returns the entire SELECT statement - not their first name:
var hisname = database.Profiles.Where(x => x.FirstName == "Jase");
What gives?
This is a C# Windows Console application.
The same code works on my website.
Update
This is what it returns to me when I try to do SELECT:
You didn't show us your connection string yet, and from your question, it's not clear if you see this behavior only when running your app from within Visual Studio or also outside of VS.
If you happen to be using SQL Server Express and the AttachDbFileName=somename.mdf approach, and you observe this behavior when running your app inside Visual Studio, then keep on reading.
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...

Categories

Resources