I'm trying to create a database in memory and run a query with .NET Core 2.1 framework. To do this I have installed a package called Microsoft.Data.Sqlite.Core and then tried to do the following:
var connection = new SqliteConnection("Data Source=:memory:");
connection.Execute("Some Create Table Query");
And my code will crash with the following error:
You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().
I've done a lot of digging to find a solution and one of them suggested calling this:
SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());
This produces me a new error:
'Unable to load DLL 'e_sqlite3' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)'
I am really lost at this point how to accomplish this. All I want to do is create an in-memory database so I can run some queries for purposes of unit testing.
I'm not sure if this is relevant but I am not using EF6, I am using Dapper and also I am using SQL Server in my actual project. I wanted to plug in Sqlite in unit tests so I can also test my queries.
I have a feeling I am using wrong packages, but looking around there are so many and I can't find any clear documentation on how to use Sqlite with MVC Core projects.
Try adding the SQLitePCLRaw.bundle_green package to your project.
dotnet add package SQLitePCLRaw.bundle_green
At that point, the following program (inspired by this) works:
using Microsoft.Data.Sqlite;
class Program
{
static void Main()
{
var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
var createCommand = connection.CreateCommand();
createCommand.CommandText =
#"
CREATE TABLE data (
value TEXT
)
";
createCommand.ExecuteNonQuery();
}
}
This is the test that I ran locally.
cd C:/temp
dotnet new console
dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.bundle_green
//
// paste the above program into Program.cs, then...
//
dotnet run
What is bundle_green? bundle_green is one of the Sqlite "bundle packages", which are expressly designed to ease cross-platform development. Here is a description from the official repository:
These packages automatically bring in the right dependencies for each platform. They also provide a single Init() call that is the same for all platforms... SQLitePCLRaw.bundle_green is a bundle that uses e_sqlite3 everywhere except iOS, where the system-provided SQLite is used.
Related
after googling and trying and failing for hours I'm resulting to stackoverflow with this issue in hopes that someone else has encountered this.
I am trying to write an integration test using MSTest for a C# project. In order to perform the integration test I need to connect to a database, we're doing database first, not code first with EntityFramework, and in all our projects we use Database.SetInitializer(null);
However, when trying to debug my test I keep receiving this exception:
The model backing the 'ApplicationDbContext' context has changed since the database was created. This could have happened because the model used by ASP.NET Identity Framework has changed or the model being used in your application has changed. To resolve this issue, you need to update your database. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=301867). Before you update your database using Code First Migrations, please disable the schema consistency check for ASP.NET Identity by setting throwIfV1Schema = false in the constructor of your ApplicationDbContext in your application.
public ApplicationDbContext() : base("ApplicationServices", throwIfV1Schema:false)
on the last line of this code block:
string connectionString = #"Data Source=MyDataSource;Initial Catalog=MyCatalog;User Id=MyUsername; Password=MyPassword;MultipleActiveResultSets=True; Trusted_Connection=False;Persist Security Info=True";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);
connection.Open();
using (MyContext context = new MyContext(connection))
MyContext has a constructor override that looks like this:
public MyContext(SqlConnection connection): base(connection.ConnectionString)
This exception of course indicates that it is unable to migrate the database, which it is not supposed to. The database is used across several projects, so Code First would not be optimal in this case.
I have tried setting
Database.SetInitializer<MyContext>(null);
In the following places:
The start of the Integration test method.
In the constructor of MyContext.
In an initializer method decorated with [AssemblyInitialize]
Neither of these seem to make any difference.
I have tried using .NET framework 6.0, 5.0 and 4.7.1 (the project that I am testing is on 4.7.1).
I have the following Nu.Get packages isntalled in the test project:
ADO.Net.Client # 1.4.3
coverlet.collector # 3.0.2
EntityFramework # 6.2.0
Microsoft.AspNet.Identity.Core #2.2.3
Microsoft.AspNet.Identity.EntityFramework # 2.2.3
Microsoft.NET.Test.Sdk # 17.2.0
MSTest.TestAdapter # 2.2.10
MSTest.TestFramework # 2.2.10
System.Configuration.ConfigurationManager # 6.0.0
System.Data.SqlClient # 4.8.3
Has anyone ever come across this issue - and how did you solve it?
I'm trying to reference dlls in my dotnet core project that are using Entity framework standard, not core.
The problem that i'm running into with dotnet core is that the connection strings that are defined in the appsettings.json are not being read by the referenced dlls, so I get the error:
Message=No connection string named 'Entities' could be found in the application config file.
In the dotnet core app I'm able to get the connection string using EF core with:
"ConnectionStrings": {
"Entities": "my connection info", // this works
},
services.AddDbContext...
This all works. The problem that I run into now is that a lot of our legacy code is .net standard, and i'd prefer to just continue to use them as libraries for now.
Where it fails in the referenced libraries is when
using (var context = new Entities()) // here
Do I need to modify the entity framework layer in the referenced libraries so that they can accept a connection string as a parameter? That would require a lot of updating very old code.
I am trying to create / connect to a Sqlite db in my razor project, using Microsoft.Data.Sqlite and EntityFramework.Sqlite nuggets packages.
My code :
public static SqliteConnectionStringBuilder connectionStringBuilder;
public static void initialiserDB()
{
connectionStringBuilder = new SqliteConnectionStringBuilder();
connectionStringBuilder.DataSource = "dbIntranet.db";
using (var connection = new SqliteConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
}
}
And I got this error (at connection.Open() line) :
Unhandled exception rendering component: You need to call
SQLitePCL.raw.SetProvider(). If you are using a bundle package, this
is done by calling SQLitePCL.Batteries.Init().
I tried multiple nuggets packages but still this issue.
Tried to call SQLitePCL.raw.SetProvider() or calling SQLitePCL.Batteries.Init(), still not working.
I know for Blazor app, a lot of project use contextDB for Sqlite db connection, but this code is way similar to what we do in our companies in C# Windows form projects.
I'm new to Blazor also :/
My project use NET Sandard 2.1
Thanks a lot for your time !
Did some research on this, but didn't find much on this topic.
I am writing an Import function to convert an SQLite database to SQL database. In the CLI version it works fine, in the Web version it falls flat on its face with an isolationLevel error. Since this is an import function it will read multiple different (same layout, version, structure; different data) sqlite databases.
The issue is when running as a Web site (multi project solution), I get 'System.Data.SQLite isolationLevel Exception' When the CLI component (standard command line app) runs. It reads the database correctly and continues on.
var connectionString = new SQLiteConnectionStringBuilder
{
DataSource = contract.FileRecord.FullPath(),
ReadOnly = true
};
var sqlHandler = new SQLiteConnection(connectionString.ConnectionString);
sqlHandler.Open();
var data = processData(sqlHandler);
sqlHandler.Close();
sqlHandler.Dispose();
Connection String is the absolute path to the database file. The database file does change depending on what is used. But the all database files have the same layout (different data).
I have tried specifying the isolation level but it still fails.
DefaultIsolationLevel = IsolationLevel.Serializable
Outside of farming this work out to the CLI in its own process, is there any way to resolve the error in the Web side?
More Specifics if needed
Multi-Project Solution
All .Net 4.5.2 targeted
VS2015
The core project that has the Import functionality (And db calls) have SQLite referenced.
The web project defines the SQL 2014 connection (working as intended)
Any ideas on how to resolve that error? (I'd give you more on the error, but that is all I get from VS2015)
Thanks!
I use EF5 over SQLite database (using System.Data.SQLite 1.0.90.0). The entities are exposed via OData service
public sealed class MyService : DataService<MyEntities>
When I query my entities from inside my app it works ok, for example
using (var ents = new MyEntities)
{
var count = ents.SomeEntity.Select(ent => ent).Count();
}
When I send a request from browser like this
http://localhost:8737/MyService/SomeEntity
it also works fine, it returns me the list of my entities.
But when I create a following request
http://localhost:8737/MyService/SomeEntity/$count
OR
I query the service by service reference from some client app (and my query contains Count()), I get an Exception
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SQLite.SQLiteException: SQL logic error or missing database
no such function: BigCount
I suppose that when the SQL request is generated it contains aggregate function BIGCOUNT which SQLite doesn't have. If I change my database provider to SQL Server, then everything is absolutely fine. I don't know what I can do to change the way the request is generated. I tried to switch to Entity Framework 6 + System.Data.SQLite 1.0.94.0 but it's no use. I tried to stick to EF5 and change the versions of System.Data.SQLite to previous ones but nothing changed. The only difference I had was that my earlier problem was "solved" (in quotes because I would not call something I don't understand a solution) when I used the EF6+SQLITE1.0.94.0.
UPDATE 23/12/2014
We solved this problem by examining the System.Data.SQLite sources, finding the place where the "bigcount" keyword was incorrectly used, fixing it for our needs and then rebuilding the library.
As stated here the BigCount should be compiled to COUNT() in all databases except SQL Server. It looks like BigCount was compiled just to BigCount, or sth like that.
Rebuilding the library turned to be tricky itself, and since I'm only a little Junior yet, so my Team Lead did that part and I can't tell the details, which I didn't have time to dive deeper in. At least, it's a direction you can use to solve the same problem.
I also encountered the error SQL logic error or missing database\r\nno such function: BigCount and here are the detailed step-by-step instructions I used to update the code to resolve the issue on a Windows operating system:
Download fossil and extract fossil.exe to your <working> directory
Open a normal command prompt
Run cd <working>
Run fossil clone https://system.data.sqlite.org/ sds.fossil
Run fossil open sds.fossil
Run fossil update <release-tag>
For example, fossil update release-1.0.105.2
Update .\System.Data.SQLite.Linq\SQL Generation\SqlGenerator.cs:
a. un-comment lines 1978 - 1983
b. replace line 1982 with the following line:
aggregateResult.Append("COUNT");
Run cd Setup
Run set_YYYY.bat
For example, to build the net451 binaries, run set_2013.bat
Run build.bat ReleaseManagedOnly
Remove the references to System.Data.SQLite.Linq and System.Data.SQLite.EF6 from the ASP.NET Web project
Add references to the new System.Data.SQLite.Linq.dll and System.Data.SQLite.EF6.dll from <working>\bin\2013\Release\bin in the ASP.NET Web project
Sources:
System.Data.SQLite Source Code
System.Data.SQLite Build Procedures
System.Data.SQLite Ticket UUID 76c2eaadc0297696b2c5fb10d41a22325f56f9b9