Database.SetInitializer(null) does not actually set it to null - c#

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?

Related

SQLite with MVC Core

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.

Integration tests broken after migrating to ASP.NET Core RC2

In my integration tests, I use a TestServer class to work towards a test server instance for my integration tests. In RC1, I instanciated it using the following code:
var server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());
On RC2, TestServer.CreateBuilder() was removed. Therefore, I tried to create a new TestServer using the following code:
var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
The problem I'm facing is that after RC2, the runtime is unable to resolve dependencies for DI, so that it throws exceptions on the Configure method for the Startup class. The system does however start up if I start the actual server (not the test project). The exception thrown is as following:
System.Exception : Could not resolve a service of type 'ShikashiBot.IShikashiBotManager' for the parameter 'botManager' of method 'Configure' on type 'ShikashiBot.Startup'.
I'm currently using the following package for the test host: Microsoft.AspNetCore.TestHost": "1.0.0-rc2-final
I needed some changes to get your repo to work:
I had to rename appsettings.sample.json to appsettings.json, I guess this is just because it's not in source control.
I had to add "buildOptions": { "copyToOutput": [ "appsettings.json" ] } to the project.json of the IntegrationTests project.
Had to change the log level Verbose to Debug in your appsettings.json.
But after this the integration test EndPointsRequiresAuthorization goes through the dependency injection, and for me it fails with an exception in ShikashiBotManager, I guess because I don't have the Postgre DB set up.
For you it already fails before this, because it cannot resolve the IShikashiBotManager interface, right?
Can you try to do a complete purge of your local repository with git clean -xfd (NOTE: your not commited local changes will be deleted), rebuild and try again?

ASP.NET MVC Type is not resolved for member MySql.Data.MySqlClient.MySqlException,MySql.Data

I added a new property to my model of an ASP.NET MVC 5.2 application with MySQL database, and now I'd like to add a database migration for this by using this command:
Add-Migration RegisterPropertyAdded
But, I get an exception:
Type is not resolved for member
MySql.Data.MySqlClient.MySqlException,MySql.Data, Version=6.9.7.0,
Culture=neutral, PublicKeyToken=c5687fc88969c44d
It seems that MySQL wants to throw an exception but can't find the exception class for reasons I don't understand. I installed the following NuGet packages in the project:
EntityFramework Version 6.1.3
MySql.Data Version 6.9.7
MySql.Data.Entities, Version 6.8.3.0
MySql.Data.Entity Version 6.9.7
In the model, the class MySql.Data.MySqlClient.MySqlException is shown, so it seems like the class exists and I can't find any information that additional packages are required for the exception class.
In order to see this exception you have to update MySQL Connector/Net
Also make sure that MySQL server is up and running and you can connect to it.
For me this message appeared due to an incorrect connection string in Web.config.

SQLite exception: "no such function: BigCount" when using "count" calling OData service with EntityFramework provider

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

DbContext crashes with PrimitiveType != null error

Using Entity Framework Code First, the web application crashes on a call to DbContext with the following error:
Assertion failed
Expression: primitiveType != null
Description: Assertion failed: primitiveType != null
It crashes on the following line of code:
public class MyDb : DbContext {
which is called by:
MyDb _db = new MyDb();
So it seams like calling DbContext generates a fatal error. DbContext is an EF function and I cannot debug inside EntityFramework.dll
It's a problem related to older versions of EntityFramework. It happens sometimes when copying a Visual Studio Project to a different machine. This can cause the application to calculate a different ModelHash than the one that is in the database (inside the EdmMetaData table). Solution is to delete the EdmMetaData table and use DbDatabase.SetInitializer<MyContext>( new DropCreateDatabaseIfModelChanges<MyContext>()); to put it back in place, or even better: Upgrade to a newer version of EntityFramework that is not utilizing the EdmMetaData table and ModelHashes.
After installing asp.net4.5 I have same error.
The Answer for me is to update Entity Framework to new version.
Deleting "EdmMetaData" table didn't resolve the error.
I swicth to linq to sql and dint get this error. Dont know what entities is doing to cause this.
You need to update your EntityFramework version

Categories

Resources