Upgrade to EF Core 7 get Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: ''.' - entity-framework-core

I upgrade Ef core 6 to 7 and get this error at Database.EnsureCreated();
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
Database.EnsureCreated();
if (Database.GetPendingMigrations().Any())
{
Database.Migrate();
}
}
The database is created but I get this error. I fear if some migrations are ended with an error and are not complete. and I want these codes always be here and not commented after first run. What is this error and how to correct it?
Edits:
I deleted all content of the Migrations folder and the Sqlite Db and created an Initial migration, But when I want to apply this migration I get the same error.
I get this error after Updating Database by a Migration or at the line:
if (Database.GetPendingMigrations().Any()):
SQLite provider.
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'main' on server 'C:\Users\...\Documents\Developer\WinForms Blazor2_2022_Book_Secure_Active\WinFormsBlazor\bin\Debug\net7.0-windows\AppData\AppDB.db'.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: ''.
I created a AppData\AppDB.db in root project folder and set this db to Copy always then in the Onconfiguring in the DbContext:
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite($"Data Source={Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))}\\AppData\\AppDB.db"
, options =>
{
options.UseNetTopologySuite();
});
}
I have no main Database, I don't understand why I have this setup worked in EF Core 6 for a year but after updating to 7 it is not working! any ideas to solve this problem?

Looks like you're hitting issue #29584. It will hopefully be fixed in version 7.0.3.
For now, you can work around it by manually updating the SQLitePCLRaw dependency:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite" Version="7.0.2" />
<!-- Manually updated to fix NetTopologySuite issues -->
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.4" />
</ItemGroup>

I find the problem was using x => { x.UseNetTopologySuite(); } in the UseSqlite function when adding the ef core context, When UseNetTopologySuite() is there, Any access to the database give error: SQLite Error 1: ''. and if I remove UseNetTopologySuite() I get another error: sqlite error 1: 'no such function: initspatialmetadata'..
In Ef core 6.0.12 there is no problem and I can use Spatial Point type without any problems, even after migrating that includes a point type, several tables and views related to geometry are created automatically with Ef core 6.
I had to forget using Spatial types in EF Core 7 so that I can upgrade my EF core version.

Related

connectionString in Entity Framework

I am stuck. I have spent nearly a day to solve but to no avail.
PROBLEM: Connecting to production database using entity framework.
I connect fine on development.
<add name="DefaultConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MONDO;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MONDOEntities" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=MONDO;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
Moving to production, I used (from the production web.config file) the existing "DefaultConnectionString" parameters (ID and Password) to edit the MONDOEntities connectionString. (can I do this?) Also, I expanded the metadata in MONDOEntities to include .csdl, .ssdl, .msl and I prefixed it with (guessing, again, can I do this?) MONDO. Bold parts are changes from dev web.config to production web.config. *Note, the connectionStrings below were not created by Visual Studio, I just changed some info myself to try and make it work on the production side.
<add connectionString="Data Source=MPOC\SQLEXPRESS;Database=Mondo;User ID=xxx;Password=xxxxx;" name="DefaultConnectionString" />
<add name="MONDOEntities" connectionString="metadata=res://*/MONDO.csdl|res://*/MONDO.ssdl|res://*/MONDO.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MPOC\SQLEXPRESS;persist security info=True;Database=Mondo;User ID=xxx;Password=xxxxx;MultipleActiveResultSets=Tru e;App=EntityFramework"" providerName="System.Data.EntityClient" />
The error message I get is:
Unable to load the specified metadata resource.
Line 62: /// Initializes a new MONDOEntities object using the connection string found in the 'MONDOEntities' section of the application configuration file.
Line 63: /// </summary>
Line 64: public MONDOEntities() :
QUESTION: Can I simply modify the connectionStrings manually or does it need to run through a compilation process? It is a website project so it compiles, on the fly, the first time after I upload to production. It does not get precompiled on my local dev computer. I guess, bottom line, how do I set up a proper connectionString for an entity connection for a database in production?
I'm on a project where I need to learn an existing website. I'm making my first bug fix and having learned ado.net, I created an entity data model and made some code changes. Everything works smooth in development.
I move the files to production and then I get this error:
"The specified default EntityContainer name 'MONDOEntities' could not be found in the mapping and metadata information.
Parameter name: defaultContainerName"
I googled this error message and based on some findings, I expanded my "metadata" shown below. This was more of a shot in dark for me:
ORIGINAL (auto generated in web.config when I created the entity data model):
connectionString="metadata=res://*
NEW (I edited/added this):
connectionString="metadata=res://*/MONDO.csdl|res://*/MONDO.ssdl|res://*/MONDO.msl;
This seemed to get past the first error and I get to a new error message (as posted in OP):
Unable to load the specified metadata resource.
Line 62: /// Initializes a new MONDOEntities object using the connection string found in the 'MONDOEntities' section of the application configuration file.
Line 63: /// </summary>
Line 64: public MONDOEntities() :
I think that there is a problem with my metadata information. However, given that the original, auto generated connectString only contains "metadata=res://*", I really don't know how to go about correcting this. Actually, I'm not even super sure that this is the root of the problem.
Bottom line, my entity model works smooth in dev but isn't connecting in production. Any thoughts are appreciated ... thanks.
The connection string has nothing to do with compilation, as long as you didn't define some transformation to be performed on it or you have some custom hooks that operate on it.
So yeah, you can modify it by hand.
You probably got those metadata wrong, try and play with them (EG removing the prefix).
Also are you absolutely sure that, in your production environment, the right connectionString is being loaded and used by the MONDOEntities?

EF Code First DbMigration without nuget

How to migrate DB without nuget? It is not possible to use Visual Studio with nuget in production environment. Currently, many examples only teach us to use Visual Studio with nuget.
How to use the generated DbMigration classes?
The easiest way is:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<MyDbContext,
MyDbMigrationsConfiguration>());
This will run the migrations when initializing the DbContext.
You can also force the execution manually:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
(I believe you also have to set TargetDatabase on the configuration, but you can try)
Here are the options:
Use the migrate.exe command line tool that ships in our NuGet
package.
Use the MigrateDatabaseToLatestVersion initializer as
others have described.
Use the runtime API available from the
DbMigrator class.
You can migrate to the latest version using a Web.config setting - see this blog post by Rowan Miller:
If you are using Code First Migrations, you can configure the database to be migrated automatically using the MigrateDatabaseToLatestVersion initializer.
<contexts>
<context type="Blogging.BlogContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Blogging.BlogContext,
MyAssembly], [Blogging.Migrations.Configuration, MyAssembly]], EntityFramework" />
</context>
</contexts>
Just swap your context class in here: the System.Data.Entity.MigrateDatabaseToLatestVersion is built-in to EF. This setting updates the old AppSettings version of the same idea.
To my mind this is the best way, because the question of which initializer to use is a configuration one really, and you want to be able to Web.config this, and ideally apply config transforms to work for your different environments.
You can do it using the EF Power Tools, there's the migrate.exe program that you can use to run migrations from the command prompt (post build for example). If you want to run migrations on production database you can also use the Update-Database command to generate SQL scripts from the migration classes, very useful if you need to pass through a DBA.
EF Power Tools are available on the Visual Studio Gallery and optionally here, check out this very useful video that, among other things, talks about the Update-Database command.
there is another solution :
Using DB = New SHAContext()
If DB.Database.Exists() Then
Dim migrator As New DbMigrator(New SHAClassLibrary.Migrations.Configuration())
For Each m In migrator.GetDatabaseMigrations()
Try
migrator.Update(m)
Catch ex As Exception
End Try
Next
End If
'DB.test()
End Using
I was looking for a way to control which migrations run explicitly in code without the need of a DbConfiguration class or automatic migrations enabled.
So i managed to create the following extension:
public static void RunMigration(this DbContext context, DbMigration migration)
{
var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
if (prop != null)
{
IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
var generator = new SqlServerMigrationSqlGenerator();
var statements = generator.Generate(operations, "2008");
foreach (MigrationStatement item in statements)
context.Database.ExecuteSqlCommand(item.Sql);
}
}
As an example, having a migration like the following:
public class CreateIndexOnContactCodeMigration : DbMigration
{
public override void Up()
{
this.CreateIndex("Contacts", "Code");
}
public override void Down()
{
base.Down();
this.DropIndex("Contacts", "Code");
}
}
You could run it using your DbContext:
using (var dbCrm = new CrmDbContext(connectionString))
{
var migration = new CreateIndexOnContactCodeMigration();
migration.Up();
dbCrm.RunMigration(migration);
}

Entity Framework with EntityDataSource throws MetadataException when installed on Windows 2008 server

I have a problem with installing a Web Application on a server which is using an EntityDataSource and the .NET Framework June CTP.
I posted the question on the MSDN Forums but still have no answer:
EF with POCO templates and DbContext throws MetadataException when installed on server
The following Exception is throwed when installing the application on a windows 2008 server with IIS 7 and when using an EntityDataSource in combination with the June CTP Framework which we need for using POCO and the DbContext.
System.Web.HttpUnhandledException (0x80004005): Exception of type
'System.Web.HttpUnhandledException' was thrown. --->
System.Data.MetadataException: Schema specified is not valid. Errors:
Library.csdl(2,9) : warning 0005: Could not find schema information
for the attribute 'Namespace'. Library.csdl(2,34) : warning 0005:
Could not find schema information for the attribute 'Alias'.
Library.csdl(2,2) : error 0010: The element Schema in namespace
http://schemas.microsoft.com/ado/2009/11/edm was unexpected for the
root element. The expected Schema in one of the following namespaces:
http://schemas.microsoft.com/ado/2006/04/edm,
http://schemas.microsoft.com/ado/2007/05/edm,
http://schemas.microsoft.com/ado/2008/09/edm. at
System.Data.Metadata.Edm.EdmItemCollection.LoadItems(IEnumerable1
xmlReaders, IEnumerable1 sourceFilePaths, SchemaDataModelOption
dataModelOption, DbProviderManifest providerManifest, ItemCollection
itemCollection, Boolean throwOnError)
When we create a test project without the June CTP Framework it is working. When we do not use the EntityDataSource with the June CTP Framework it works too. We developed some months with this EntityDataSource so it's not easy to change the code and use something else.
Your server appears to have .NET 3.5 SP 1, and the CTP requires .NET 4. The schemata in the error message (2006-8) are EF 10 2009/11/edm are EF 4.

Format of the initialization string does not conform to specification starting at index 0

I have an ASP.Net MVC application which runs fine on my local development machine. But when deployed to IIS7 gives the following error when trying to log in:
Format of the initialization string does not conform to specification
starting at index 0
Most people who post this error resolve it by changing their connection string in some way. However my connection string on the local and deployed application are the same. The connection string is like this:
<add name="ApplicationServices" connectionString="Data Source=*server*\*instance*;Initial Catalog=*database*;Integrated Security=True;"
providerName="System.Data.SqlClient" />
What is causing this error in my case?
Format of the initialization string does not conform to specification
starting at index 0
Web.config :
<connectionStrings>
<add name="TestDataConnectionString" connectionString="Data Source=.\SQLExpress;Initial Catalog=TestData;User ID=satest;Password=satest"
/>
</connectionStrings>
In aspx.cs Page the code must be written in the below format :
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["TestDataConnectionString"].ToString());
Web Deployment tool created wrong line in config when I checked Enable CodeFirst Migrations check-box.
In my case I accidentally wrote "password:" instead of "password=" in my conn string
Check to make sure the credentials are correct for the connection string in Web.config. Mine was missing the password for the account with permissions to the database.
I encountered the same error. In my case it was the config transform not working properly.
There is an issue with config transforms when it comes to connection strings.
Some reference:
MSBuild web.config transforms not working by drneel
Replaceable token issue with config ConnectionString transforms by Francis
Also one can write the code in the aspx.cs page as
using (IDbConnection dbConnection =
new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
// TODO: Write SQL Stored Procedures or SQL Statements using Dapper
}
For those who would like to find out more about Dapper.
Hope this helps.
If you have been using the Visual Studio Publish Wizard for deployment and checked the Execute Code First Migrations check box in Settings, a new ConnectionString is automatically added to the Server Web.config file, similar t to the 2nd line below:
<add name="LCWeb3Context" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LCWeb3;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\LCWeb3.mdf" providerName="System.Data.SqlClient" />
<add name="LCWeb3Context_DatabasePublish" connectionString="LCWeb3Context_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
First, notice the added connection string contains "ConnetionString": I think it should be "ConnectionString"! But that's not the solution.
To avoid the "Format of the initialization string does not conform to specification starting at index 0" error, do the following in the Publish Wizard:
In the Settings, select Configuration: Release
In the Settings,don't forget to paste your Connection String in the
"Remote Connection String" field
In the Settings, check Execute Code First Migrations
When doing the above, the connection string added to the Server Web.config reads:
<add name="LCWeb3Context_DatabasePublish" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LCWeb3.mdf;Initial Catalog=LCWeb3;Integrated Security=True" providerName="System.Data.SqlClient" />
and the "Format of the initialization string does not conform to specification starting at index 0" error no longer occurs.
I has the same issue, when I use command: "Update-Database" in Package Manager Console.
To Fix, make sure set startup project to the project which you want to do update.
E.g. I got Db project and Web project, make sure set startup project on Db project, when run "Update-Database", otherwise, it will try to search inside Web project.
The permissions on the SQL server were not correctly set up. I have now resolved this by properly setting up the server permissions.

Seam 2.2GA + JBoss AS 5.1GA + Postgres 8.4

Sorry for the big wall of text, but its mostly logs
Thx for any help in any of my problems
I've been trying to get help from Seam forums, but in vain.
I'm trying this Setup mentioned in the title, but unsuccessfully.
I have it all installed correctly and the problems start with the seam-gen.
This is my build.properties
#Generated by seam setup
#Sat Aug 29 19:12:18 BRT 2009
hibernate.connection.password=abc123
workspace.home=/home/rgoytacaz/workspace
hibernate.connection.dataSource_class=org.postgresql.ds.PGConnectionPoolDataSource
model.package=com.atom.Commerce.model
hibernate.default_catalog=PostgreSQL
driver.jar=/home/rgoytacaz/postgresql-8.4-701.jdbc4.jar
action.package=com.atom.Commerce.action
test.package=com.atom.Commerce.test
database.type=postgres
richfaces.skin=glassX
glassfish.domain=domain1
hibernate.default_schema=Core
database.drop=n
project.name=Commerce
hibernate.connection.username=postgres
glassfish.home=C\:/Program Files/glassfish-v2.1
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider
jboss.domain=default
project.type=ear
icefaces.home=
database.exists=y
jboss.home=/srv/jboss-5.1.0.GA
driver.license.jar=
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.connection.url=jdbc\:postgresql\:Atom
icefaces=n
./seam create-project works okay, but when I try generate-entities, I get the following...
generate-model:
[echo] Reverse engineering database using JDBC driver /home/rgoytacaz/postgresql-8.4-701.jdbc4.jar
[echo] project=/home/rgoytacaz/workspace/Commerce
[echo] model=com.atom.Commerce.model
[hibernate] Executing Hibernate Tool with a JDBC Configuration (for reverse engineering)
[hibernate] 1. task: hbm2java (Generates a set of .java files)
[hibernate] log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
[hibernate] log4j:WARN Please initialize the log4j system properly.
[javaformatter] Java formatting of 4 files completed. Skipped 0 file(s).
this is problem no.1. How do I fix this? What is this? I had to do this in eclipse. It worked.
Then I import the seam-gen created project into eclipse, and deploy to JBoss 5.1. While my servers start I've noticed the following..
03:18:56,405 ERROR [SchemaUpdate] Unsuccessful: alter table PostgreSQL.atom.productsculturedetail add constraint FKBD5D849BC0A26E19 foreign key (culture_Id) references PostgreSQL.atom.cultures
03:18:56,406 ERROR [SchemaUpdate] ERROR: cross-database references are not implemented: "postgresql.atom.productsculturedetail"
03:18:56,407 ERROR [SchemaUpdate] Unsuccessful: alter table PostgreSQL.atom.productsculturedetail add constraint FKBD5D849BFFFC9417 foreign key (product_Id) references PostgreSQL.atom.products
03:18:56,408 ERROR [SchemaUpdate] ERROR: cross-database references are not implemented: "postgresql.atom.productsculturedetail"*
03:18:56,408 INFO [SchemaUpdate] schema update complete
Problem no.2. What is this cross-database references?
What about this..
03:18:55,089 INFO [SettingsFactory] JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 8.4 JDBC3 (build 701)
Problem no.3 I've said in the build.properties to use JDBC4 driver, I don't know why seam insists to use JDBC3 driver. Where do I change this?
When I go into http://localhost:5443/Commerce and try to browse the auto-generated CRUD UI.
I get this error.. Error reading 'resultList' on type com.atom.Commerce.action.ProductsList_$$_javassist_seam_2
And this is what is showing in my server logs...
03:34:00,828 INFO [STDOUT] Hibernate:
select
products0_.product_Id as product1_0_,
products0_.active as active0_
from
PostgreSQL.atom.products products0_ limit ?
03:34:00,848 WARN [JDBCExceptionReporter] SQL Error: 0, SQLState: 0A000
03:34:00,849 ERROR [JDBCExceptionReporter] ERROR: cross-database references are not implemented: "postgresql.atom.products"
Position: 81
03:34:00,871 SEVERE [viewhandler] Error Rendering View[/ProductsList.xhtml]
javax.el.ELException: /ProductsList.xhtml: Error reading 'resultList' on type com.atom.Commerce.action.ProductsList_$$_javassist_seam_2
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute query
Problem no.4 What is going on here? Cross-database references?
Thx for any help in any of my problems.
You did receive a few answers on the Seam forums (here and here), but you didn't follow up. Anyway, all these are actually caused by one problem:
As Stuart Douglas told you, you shouldn't use a catalog when connecting to PostgreSQL. To fix this, replace the property "hibernate.default_catalog=PostgreSQL" in your properties file by the property: "hibernate.default_catalog.null=", so that your file looks like this:
...
model.package=com.atom.Commerce.model
hibernate.default_catalog.null= # <-- This is the replaced property
driver.jar=/home/rgoytacaz/postgresql-8.4-701.jdbc4.jar
...
You should be able to use seam generate-entities fine afterwards (assuming the rest of your configuration is correct). I'd recommend doing the generation into a clean folder.
Cross-database references is when a query tries to access two or more different databases. PostgreSQL does not support this, and thus complains when there is more than 1 period in the table name, so in PostgreSQL.atom.productsculturedetail, the bold part should be removed. Hibernate adds this prefix when you tell it to use a default catalog, which we already fixed in step 1 above (by telling it not to use a catalog), so this problem should be fixed after you regenerate your entities.
(Note that this is effectively the same as what Stuart Douglas told you, that you should remove the catalog="PostgreSQL" attribute in the annotations on your entity classes.)
When you specified the postgresql-8.4-701.jdbc4.jar file in the properties file, this didn't mean that the driver supports JDBC4. Although the name of the file would suggest so, the driver's website clearly states that "The driver provides a reasonably complete implementation of the JDBC 3 specification". This shouldn't be a problem for you, as you're not using the driver directly (or at least you're not supposed to). The driver is sufficient for Hibernate to fulfill its requirements and provide the required functionality.
This issue is caused by the same problem above. Hibernate is unable to read data from the database because of the incorrect query. Fixing the catalog problem should fix this issue.