I have connected to my SQL Server Compact Edition database from an ASP.NET console application. I am using the same thing and libraries to connect to SQL Server CE database file in my ASP.NET Core Web API application, but I get an exception.
My code:
public class ClienDetailRepository: IClientDetailRepository
{
private readonly string _connectionString;
private static string DbFilePath = @"C:\Git\Forecaster\DB\THSTaxPro.sdf";
private static string DbPassword = "*****";
private static string DbMaxSize = "4090";
public static string ConnectionString = @"Data Source=" + DbFilePath + ";Password=" + DbPassword + ";Max Database Size=" + DbMaxSize + "";
public ClienDetailRepository(string connectionString)
{
_connectionString = connectionString;
//_connectionString = ConnectionString;
}
}
I am getting error on this line
SqlCeConnection sqlconTHS = new SqlCeConnection(ConnectionString);
This is the error:
The type initializer for 'System.Data.SqlServerCe.SqlCeConnection' threw an exception
Do you use Windows? I tested on Windows, and your problem did not occur, you can refer to my steps below.
Copy the
System.Data.SqlServerCe.dllfile and the entireamd64folder from theMicrosoft SQL Server Compact Edition\v4.0\Private directoryto the folder where the.csprojfile created:Install the Windows compatibility pack, to make any required Windows specific .NET APIs available.
Add a file reference to the
System.Data.SqlServerCe.dllfile in the root of your project, and your .csproj file should end up like this(I'm using .net6):My Test Code:
Of course, please make sure your connectionString is correct.
Test Result:
For more detail, you can refer to this link.