SQLite attempt to write a readonly database error - c#

I have a console application that populates a SQLite database. When the application runs by itself, I don't get any errors. If I run multiple instances of the application, where each application is in its own folder and each populates its own database I'll occasionally get the following exception:
System.Data.SQLite.SQLiteException (0x80004005): Attempt to write a read-only database
attempt to write a readonly database
at System.Data.SQLite.SQLite3.Reset(SQLiteStatement stmt)
at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
I know the DB isn't read-only because it has already written data to that database. Also, the app continues on and will continue populating data to that database. I haven't reproduced the error when only a single instance of the application is running.
I've tried using the pragma to have both the journal and temp_store in memory instead of to a file in case there could be some contention across applications there, but I still get the error. I do always get the error in the same method, which is the first time an insert would happen for the connection. To give a general idea of what the application does, it loops over cases, gathers info about those cases (not from SQLite), then writes results to the SQLite database.
I don't know what else to try.
*edit
I am also using the PRAGMA journal_mode=MEMORY. When inserting data into the SQLite database, I first run a BEGIN statement, then a bunch of inserts before the END statement. The error occurs on the first insert.

It is a permissions issue.
Make sure that your web application that is hosted has add/write/create/delete access to the folder where the sqlite database resides.
For more details, refer this

Could also be that The database file is not supported by the MigrationAssembly.
The same exception is thrown when the EF tries to migrate on a file expected to be a SQLite database which is fi. a text file.

Related

Database and database schema suddenly out of sync

I have (I think) a very strange problem.
I have a web server running an ASP.NET MVC app querying a SQL Server database. It has all been constructed using code-first approach.
It has been working without problems for a long time, and whenever I have needed e.g. a new column in a table, I have added the needed class to the model in question. Then I have run Add-migration 'Migration_Name', and a script has been generating with the proposed changes, and after running update-database, the changes have been applied to the database. Easy and always working.
Yesterday, without making any changes to the database or the models (and by the way not even updating the web-server) it stopped working.
The database throws an error the moment the web-app tries to access the database
System.Data.SqlClient.SqlException: 'CREATE TABLE permission denied in database 'master'
The content of the database is intact I can see from browsing it from within Visual Studio.
If I run the add-migration command, a script is generated for every single table, column, foreign key etc for the entire database, as if the database did not contain a single one of the classes defined in the models.
So it seems that the database is not in sync with my code first models anymore. I got my IT department to copy the entire database to a test server to try to test what is wrong without messing up the production database, and after trying to run the "strange" migration script by using the update-database command, I get the same error:
CREATE TABLE permission denied in database 'master'
and it shows me that it fails when trying to create the first table in the migration script. This is not surprising, since it already exists in the database. But what is going on - I am at a loss!
So can anyone tell me might have happened here, and more importantly, how to fix it?
All the best
Troels

System.Data.Entity.Core.ProviderIncompatibleException

so basically at work I was assigned an old ASP.NET project which is outdated I have couple of months debugging it. Last week the project was working fine then from one moment to another stopped working. When I run the project I get this exception
System.Data.Entity.Core.ProviderIncompatibleException: 'An error
occurred accessing the database. This usually means that the
connection to the database failed. Check that the connection string is
correct and that the appropriate DbContext constructor is being used
to specify it or find it in the application's config file. See
http://go.microsoft.com/fwlink/?LinkId=386386 for information on
DbContext and connections. See the inner exception for details of the
failure.'
Which also have 2 inner exceptions
ProviderIncompatibleException: The provider did not return a
ProviderManifestToken string.
OracleException: ORA-00604: error occurred at recursive SQL level 1
ORA-12705: Cannot access NLS data files or invalid environment
specified
What is causing this error?
When I run the project I have a method called LoadUserInfo(); which displays the user code, user department and username to retrieve this data, the application goes to the oracle database and retrieves this info, but for some reason (that I cant figure out) is not working.

How do I add columns to database without users losing data when a new version of the application is published?

I have a c# .NET application with a SQLLocalDB database. I have used database first to create the EF6 model. I have added columns to one of the tables using SQL Server Management Studio and then used 'Update model from database' to propagate the changes into my model. When doing this, data on the development PC is unaffected and incorporates the new columns. However, when a different user runs the new version of the application, their existing datafile (.mdf) won't recognise the new columns and crashes with the exception:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid column name 'VAT_long_description'
making the user's existing data in that table unreachable. I appreciate that Code First gives the ability to migrate data, but this facility appears not to be available when building the EF model using database first.
My connectionString is:
<add name="PMMEntities" connectionString="metadata=res://*/PMMData.csdl|res://*/PMMData.ssdl|res://*/PMMData.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\v11.0; AttachDBFilename=|DataDirectory|\PMM.mdf; initial catalog=PMM;Integrated security=True;MultipleActiveResultSets=True; App=EntityFramework""providerName="System.Data.EntityClient" />
I want to ensure that when a user installs a new version, their .mdf datafile will adapt to the new database schema without loss of data. It seems the only way to do this is through running a conversion or migration method on startup if the app throws the “Invalid column name” SQL exception. Where can I find the code (or a NuGet package) that will do this?
if you are using MVC , you have two methods to make an update in your models class database. the most easy way to resolve that issue is that you delete the model class related to the database and you import it again into your model folder. don't worry about data, they will still stored in your database. unless you have wrotten some extra object in the model class database, in this case you will waste those extra objects.. it will not affect your storage.

C# localdb SHRINKDATABASE command from C# code

I'm trying to shrink a LocalDb with Visual Studio 2017 Community. I have a Win7 client windows form application with a small database (~10MB of data) that results into 150MB database size due to LocalDb free space allocation.
I found this answer (Executing Shrink on SQL Server database using command from linq-to-sql) that suggest to use the following code:
context.Database.ExecuteSqlCommand(
"DBCC SHRINKDATABASE(#file)",
new SqlParameter("#file", DatabaseTools.Instance.DatabasePathName)
);
DatabaseTools.Instance.DatabasePathName returns the filesystem location of my database from a singleton DatabaseTools class instance.
The code runs, but I keep getting this exception:
System.Data.SqlClient.SqlException: 'Cannot perform a shrinkdatabase operation inside a user transaction. Terminate the transaction and reissue the statement.'
I tried COMMIT before, but no success at all. Any idea on how to effectively shrink database from C# code?
Thanks!
As the docs for ExecuteSqlCommand say, "If there isn't an existing local or ambient transaction a new transaction will be used to execute the command.".
This is what's causing your problem, as you cannot call DBCC SHRINKDATABASE in a transaction. Which isn't really surprising, given what it does.
Use the overload that allows you to pass a TransactionalBehavior and specify TransactionalBehavior.DoNotEnsureTransaction:
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
"DBCC SHRINKDATABASE(#file)",
new SqlParameter("#file", DatabaseTools.Instance.DatabasePathName)
);

SqlCeException when attempting to delete rows from table in sdf database (Corruption?)

I attempt to delete a number of rows from a table in a SQL Server CE 3.5 database and I get a SqlCeException:
An internal error occurred. [ ID = 3649 ]
I've read that it means that the database is in a corrupted state and must be repaired although there is little information about the specific error.
I use the SqlCeEngine.Verify() and it returns true. According to MSDN
Returns True if the checksums match and there is no database corruption; otherwise, false.
I also use the SqlCeEngine.Repair(null, RepairOption.RecoverCorruptedRows);
and then attempt to delete the rows again and the command is executed without any errors and rows are deleted.
I'm confused is it or not the db corrupted? I think it is (but the verify returns true). If it is corrupted how it became corrupted? I create a new connection for every database access and I don't share the same SqlCeConnection objects between threads (or any other SQL Server CE related objects) The database is deployed on a mobile device.

Categories

Resources