8

I am creating SQLite In Memory database for unit testing:

        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        try
        {
            var options = new DbContextOptionsBuilder<BloggingContext>()
                .UseSqlite(connection)
                .Options;

            // Create the schema in the database
            using (var context = new BloggingContext(options))
            {
                context.Database.EnsureCreated();
            }

            // Run the test against one instance of the context
            using (var context = new BloggingContext(options))
            {
                var service = new BlogService(context);
                service.Add("http://sample.com");
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new BloggingContext(options))
            {
                Assert.AreEqual(1, context.Blogs.Count());
                Assert.AreEqual("http://sample.com", context.Blogs.Single().Url);
            }
        }

context.Database.EnsureCreated(); fails with with exception: Message: Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'near "MAX": syntax error'.

There is github issue saying: The issue here is varchar(max) is SqlServer specific type. The scaffolding should not add it as relational type which gets passed to migration in other providers which is prone to generate invalid sql at migration.

But how then can I use SQLite in Memory for unit tests if my database contains many varchar(max) columns?

4
  • If you're using EF Core, why not use the In Memory provider instead of SQLite?
    – DavidG
    Nov 30, 2018 at 15:36
  • @DavidG I am using "In Memory SQLite Database" link because I need to test transactions. Nov 30, 2018 at 15:39
  • If you use 'Migrate' instead of 'EnsureCreated'?
    – Silvermind
    Nov 30, 2018 at 15:44
  • @Silvermind I tried this but then I am getting another exception. When I call _offerContext.Set<Aggregate>().FindAsync(id); I am getting exception: typeof(Microsoft.Data.Sqlite.SqliteException): SQLite Error 1: 'no such table: Offers'. ---- Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'no such table: Offers'. instead of null. If am passing id with existing entity it return correct object. But I want to test behaviour when I don't find an entity. Nov 30, 2018 at 15:54

2 Answers 2

0

I didn't find a direct solution but have started using a Configuration files workaround. You didn't indicate if you're using EF Configurations so excuse the basics if not needed.

In your DbContext place the following:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(ChildrensSsiContext).Assembly);
}

Now create a static class like below. It's going to take your property and handle the configuration.

internal static class ConfigurationHelper
{
    internal static void ConfigureVarcharMax(PropertyBuilder<string> propertyBuilder, bool isRequired = true)
    {
        propertyBuilder
            .IsRequired(isRequired)
            //.HasColumnType("varchar(max)");
            .HasColumnType("text");
    }
}

Create a Configuration class for each entity that you want to configure

public class MyEntityWithVarcharMaxConfiguration
    : IEntityTypeConfiguration<MyEntityWithVarcharMax>
{
    public void Configure(EntityTypeBuilder<MyEntityWithVarcharMax> builder)
    {
        ConfigurationHelper.ConfigureVarcharMax(builder.Property(e => e.MyVarcharMaxProperty));
    }
}

Leave the HasColumnType("text") uncommented for testing. Then comment that line and uncomment the HasColumnType("varchar(max)") when you add the migration.

It's a pain that you need to remember to do this but it's a fairly simple workaround.

0

My workaround: define a flag in the AppDbContext as true (in my case, meaning this is for my SqlServer). Whenever the AppDbContext gets initialized from the Test project, set the flag to false (since for tests we use SqlLite).

Finally, in the OnModelCreating for those entities with nvarchar(max) check the flag and if false (meaning I am running the tests) set the ColumnTypes for those nvarchar(max) properties to Text.

In AppDbContext:

public static bool IsSqlServer = true;

In AppDbContext.OnModelCreating for the entities with those nvarchar properties do the following to change the type from nvarchar(max) to text:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<YourType>( entity => 
   {
      if (!IsSqlServer)
         entity.Property(YourPropertyName).HasColumnType("text");
   }
}

Finally, in your test project initialize, set the flag to false to change the types so it doesn't fail.

AppDbContext.IsSqlServer = false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.