Entity Framework SaveChanges is not working - c#

I have a C# winforms application, and a SQL Server .mdf database file.
I tried to use Entity Framework. It works great when retrieving data from the database, but on calling .SaveChanges() nothing happens. No error, no exception, and no changes saved.
This issue just drives me crazy. I found a bunch of questions with nearly the same issue, but neither of the answers apply to my case.
My code looks like that:
using (World_ParkingEntities context = new World_ParkingEntities())
{
client _client = context.CreateObject<client>();
_client.name = name;
_client.mobile_number = phoneNo;
_client.email = email;
context.AddToclients(_client);
context.SaveChanges();
}
My connection string:
<add name="World_ParkingEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\World_Parking.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /></connectionStrings>

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 after the context.SaveChanges(); 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. World_Parking)
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=World_Parking;Integrated Security=True
and everything else is exactly the same as before...

Related

Entity Framework won't save changes in database

When I try to add an item into the database, after running the app the data won't be in the database for long time memory. I don't know why, the connection is good and I already checked it many times.
private void InsertIncomeBtn_Click(object sender, RoutedEventArgs e)
{
float lf = (float)Convert.ToDouble(IncomeText.Text);
MessageBox.Show(lf.ToString());
DateTime date = (DateTime)MovDatePick.SelectedDate;
Movments mv1 = new Movments();
mv1.Sum = lf;
mv1.Date = date.Date;
db.TotalAll.FirstOrDefault().CurrentSum += lf;
db.Movments.Add(mv1);
db.SaveChanges();
IncomeWin.Close();
MainWindow m = new MainWindow();
m.Show();
}
I am using VS 2017 Community and writing a WPF app.
Thank for helping.
I'm assuming (from a lot of previous questions) that you have a SQL Server database, and your connection string most likely contains an AttachDbFileName=..... entry - correct?
If so: the whole 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. YourDatabase)
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=YourDatabase;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.

Local DB in Visual Studio 2015

After a few years, I have returned to writing in C# and I am really struggling here - I would like to have my app to have a local SQL database. I have added Service-based database and "Database1.mdf" was added to my project. I created a table and added some data just to see if it is working but I cannot connect to it. I tried numerous connection strings with no success (Server not accessible).
Do I need to run something else in the background? I thought that I might have a local database and with .NET client I can access it, and I hoped it would work whenever I bring my application (also not requiring any SQL server running). Is that wrong?
If you don't require any SQL server, take a look at SQLite. This is lite SQL database engine. Database is just one file. C# has a great library to SQLite on NuGet: https://www.nuget.org/profiles/mistachkin
SQLite is widely used, event in Android (as a native db engine).
here is what i use to connect. it appears as a Data Connection in Server Explorer.
string con2 = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Application.StartupPath + "\\jobfile_2017.mdf;Integrated Security=True;Connect Timeout=30";
when i first started working with these, i used this source 1
it works on PC's that i have nothing installed (not even office) but as i said i'd be interested to know of any shortcomings of this method
I experiencing same problem and decided to move mdf file to static c:\db directory. Connection string was changed to incorporate new file location (AttachDbFile).
But AttachDbFile has some issues also (by some reason one table in db is inaccesible and error is access denied).
So I decided to move to Sqlite. LocalDb has many issues to work with. I read good note to resolve problem: in command line stop/remove/start name of instance. But it nuissance.
Wish you good luck to work with these db files.

Error attaching existing database entity framework code first

I have created an application using Entity Framework 6 code-first, in ASP.NET MVC 5, and am bin deploying it to my server. Everything works fine, except for the operations/controller actions that involve database usage.
I am uploading the once-generated database file from my computer to the App_Data folder of the server.
Upon deploying, I changed the connection string in my web.config file from:
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-NERC_Main-20160104065223.mdf;Initial Catalog=aspnet-NERC_Main-20160104065223;Integrated Security=True"
to
connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\aspnet-NERC_Main-20160104065223.mdf;Initial Catalog=aspnet-NERC_Main-20160104065223;Database=aspnet-NERC_Main-20160104065223.mdf;Trusted_Connection=Yes;Integrated Security=True;"
which throws an error of
CREATE DATABASE permission denied in database 'master'.
A probable cause of this is because the present database file is not being attached, and the entity framework is trying to generate a new database in some other, restricted directory.
I read that the AttachDbFileName is valid for SQL Server Express instances only, which in my case doesn't exist.
How can I modify the connection string so that my current, already uploaded database is utilized.
Note:
The remote server has a full installation of SQL Server 2008 R2. The server does not support user instances. My database is not password protected, and hence I've set the Integrated Security property value to True. I'll provide any other information if required.
If you have a full version of SQL Server, you cannot just use AttachDbFileName. Instead, you need to copy the .mdf (and .ldf) to the SQL Server data file location and then you need to attach the database in SQL Server Management Studio to the server instance.
From that point on, you can reference that database in your connection string using the server name, and the logical database name - something like this:
Server=.;Database=aspnet-NERC_Main-20160104065223;Integrated Security=True;
Depending on your database setup, you may or may not be able to use the Integrated Security - maybe you'll need to have a specific SQL Server login and specify that login (and its password) in your connection string instead:
Server=.;Database=aspnet-NERC_Main-20160104065223;User ID=YourUserName;Password=YourPassword
See this site here for a ton of sample of how to build valid connection strings for SQL Server.

Can't access mdf file in desktop application

I need your help.. maybe it's the small task which I am not able to solve but I don't know how to search that on any search engine
I am using an .mdf file (vs 2103) in my WPF login register desktop application.. Everything is working fine, no compilation errors. I inserted some data into the .mdf file by using query in Visual Studio and then try to login through application and it's working fine. Moreover I am also able to register, i.e., insert into .mdf file from the register option of application if I use the "absolute path" of the .mdf file. Problem begins when I try to insert into .mdf file using a "relative path"... it doesn't insert data into the .mdf....I don't know why.
(this absolute path is not working. I have .mdf file in the database folder)
//connection string
connetionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database\Database1.mdf;Integrated Security=True";
//code
SqlCommand sqlCmd;
string sql = null;
SqlConnection sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sql = "insert into [NewTable] ( Name , Password ) values ('ABC' , '12345')";
sqlCmd = new SqlCommand(sql, sqlCnn);
sqlCmd.ExecuteNonQuery();
sqlCnn.Close();
MessageBox.Show("You have Been Registered");
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
It shows the message "You have Been Registered"
but is not visible in .mdf file...
I want to ask..why is it behaving like this....and I want to use the relative path as we cant judge the client system absolute path...what mistake I am doing? how to handle this (i guess self made) issue?
The whole 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...
Also see Aaron Bertrand excellent blog article Bad habits to kick: Using AttachDbFileName for more in depth explanations and tips

Backup Sql Express

I would like to be able to run an on demand backup of a .Net MVC app's SQL Express 2008 database to eg a flash stick plugged into the machine running the app.
I tried
QuickstemDataContext db = new QuickstemDataContext();
string quickstem_path = Path.Combine(save_path, "quickstem.backup");
db.ExecuteCommand(string.Format("BACKUP DATABASE {1} TO DISK = '{0}' WITH COMPRESSION;", quickstem_path, db.Mapping.DatabaseName));
But get the exception
Database 'quickstem' does not exist. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally
I am using the following connection string.
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quickstem.mdf;Integrated Security=True;User Instance=True"
Do I need to attach the DB using something like Express Management Studio and give it a name etc. Ideally I want to keep the app deploy very simple without having to setup sql management studio etc. Can this attaching be done another way or can a Backup be done with out needing to attach
I tried giving it the full path of the .mdf file instead of the database name but got a syntax error on c:
You'll find that if you add Database=Quickstem to your connection string, your backup code will work just fine.
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quickstem.mdf;Integrated Security=True;User Instance=True;Database=Quickstem

Categories

Resources