c# DataContext CreateDatabase isn't working, if database-file is deleted - c#

I create an application, which uses a local database, which is stored in the AppData folder. I created a DataContext to get the data:
private NorthWindDataContext northWindDataContext = new NorthWindDataContext(connectionString);
At each start of the application, it checks if the database exists. If it not exists, it should create the database:
DB:
if (!northWindDataContext.DatabaseExists())
{
try
{
northWindDataContext.CreateDatabase();
}
catch (Exception ex1)
{
try
{
northWindDataContext.DeleteDatabase();
}
catch (Exception ex2)
{
}
}
goto DB;
}
This works fine, but if I delete the file in the directory and start the application again I get the following Exeception, when it creates the database using CreateDatabase:
"Database 'C:\Users\me\AppData\Local\Test\Northwind.mdf' already exists. Choose a different database name."
If the CreateDatabase-method fails, it should delete the database (which actually not exists) using DeleteDatabase. Here is not an Exception thrown by the application. Then it should try to create the database again. Now the application doesn't throws the Exeception at CreateDatabase, but it is also not a database-file created.
This happens at each start of the application, if the database-file is deleted by the user, so what am I doing wrong or is there something missing?

The data context is using by default an instance of localdb ... deleting the database file (the .mdf file) doesn't mean that the database doesn't exist in this instance of localdb anymore. You can confirm that by deleting any .mdf file and querying the master database of the server
select * from sys.databases
You will find that the database already exists even after deleting the file , that's why you are getting the database exits error if you tried to create the database and probably the condition !northWindDataContext.DatabaseExists() won't be met cause localdb thinks it still has the db
I tried to open SQL Server Management Studio and delete the database from there then i got a file not found error and at this moment localdb noticed that the database has been removed and it has removed it from the object explorer and the sys.databases view

Related

How to open SQLite database while debugging in VS 2019 C# UWP

I've read a ton of articles on this topic but still not able to overcome the problem.
Standard code to open a database:
using Microsoft.Data.Sqlite;
string _dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "orders.db");
using (SqliteConnection db = new SqliteConnection($"Filename={_dbPath}"))
{
db.Open();
etc.
}
The system doesn't produce any error and the databse has Open state. But it's not my database! It seems the system open new empty database (I can create tables, isert/read records there) instead.
Can anybody explain me what I should do to be able to work with my existing database?
I set Mode=ReadWrite - now the new database is not created and produces the error: cannot open db
The database is located in the project root directory.

Error in installing c# application in database

I have a windows application in C#, my connection string is:
and my database is in SQL Server 2008 R2.
but when I installed my program I receive This error:
Please help me I don't know how to solve this
As I guessed, you are (attaching is) creating a new database.
You are facing this problem because there is already a database in that server with the same Db name and primary file name. This is probably (mostly) due to adding the Db twice.
Please open SQL-Server Management Studio, and check the already existing Db of name IcuProject. If it's the same Db that you wanted to attach, then skip attaching part or delete the current db from server and try attaching it again.
As a best practice, if you are attaching a db thru application, then make sure that no db with same name already exists in the server. or best, ask user to enter a Db name so that you won't get a name conflict.

How to copy mdf file into a folder with c#

I'm using c# and I have a small SQL Server database that I need to copy into a folder C:\databases\, the method name is CreateCopy.
But at File.Copy row appear an error:
"The Process cannot Access the File, because it is being use by another Process"
I read that File.Copy can be execute only after shut SqlServer down or Detach that database, create a copy and turn SqlServer on again. But how to do it by code?
This is the method that I was trying to use:
public static void CreateCopy()
{
try
{
DateTime date = DateTime.Now;
SqlConnection connection = new SqlConnection(MDF_CONNECTION_STRING);
String dbpath = String.Format(#"C:\databases\{0:yyyyMMdd}.mdf", Cash, date);
File.Copy(#"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\database.mdf", dbpath);
String lgpath = String.Format(#"C:\databases\{0:yyyyMMdd}_log.ldf", Cash, date);
File.Copy(#"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\database_log.ldf", lgpath);
}
catch(Exception e)
{
throw new ApplicationException("Error", e);
}
}
Thanks in advance!
INFO
This is not a duplicate of here because i don't need to do create a bak file, i need to archive this database. I need just to copy these two files (.mdf and .ldf) into a folder. And that answers didn't help me
What I understand is that you are looking for the code which will help you to Programmatically Enumerating, Attaching, and Detaching SQL Server Databases So that you can copy the MDF file to the location. You can also have a look on How to Backup and Restore to get the idea of AttachDbFilename mode.
Database files .mdf and .ldf files are used by the SQL Server engine.
If you DETACH database from SQL Server instance, then you can copy or move those files.
But when you DETACH db, it will be unaccessible!
So it is better to run a backup command in SQL then use it.
Remove SqlConnection connection = new SqlConnection(MDF_CONNECTION_STRING); it will access the .mdf file and give it after the File.Copy() execute. because at the time of execution of File.Copy() the file is being used by SqlConnection that's because you are getting such error

LocalDB location

I'm using LocalDB and Entity Framework code-first for a new project. I want to change the location where the database is created/saved. However, every time I do, I get one of any number of exceptions. If I try adding AttachDBFilename=|DataDirectory|\database.mdf, I get an exception stating:
The underlying provider failed on Open.
As well as:
Cannot attach the file 'C:\Projects\database.mdf' as database 'Schema.MyProject'.
Eventually, when I run this program on another computer, I'm looking to create/save the database in the AppData folder. How can this be done?

How to insert into SQL Server Compact

I am working with .NET 4.5 and C# using a SQL Server Compact database.
Here is the insert command I am using:
try
{
conn.Open();
String query = "INSERT INTO categories (cat_title) VALUES (#cat_title)";
SqlCeCommand cmd = new SqlCeCommand(query, conn);
cmd.Parameters.AddWithValue("#cat_title", cat_title);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
After I do this, I immediately get results from the table to populate a combobox. I can see the newly added item.
However, when I go back to the Database Explorer, the items are not there. If I run the app again, I can see the item or items I added.
If I refresh the dB from the Database Explorer, the results are not longer present in the app.
Am I doing this right? Why would the results behave this way?
#marc_s and #ta.speot.is are correct, but for the other newbies out there I think I might also chime in.
The database that you see in the explorer is reading a different instance of the .sdf file than the one your connection string is referencing. It is possible that the explorer is reading the .sdf file from your main project directory, while your connection string is connecting to the .sdf file in you bin/debug/ folder. If this is the case, the .sdf file that your connection string references will be overwritten every time the program runs.

Categories

Resources