question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

DELETE FROM <table name> does not work as expected in EF Core when using the Microsoft.Data.Sqlite driver

See original GitHub issue

To Reproduce

Call context.Database.ExecuteSqlInterpolated($"DELETE FROM {tableName}") or call context.Database.ExecuteSqlRaw("DELETE FROM {0}", tableName).

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<ApplicationContext>();
                DbInitializer.Initialize(context);
            }
            catch (Exception e)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(e, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddDbContext<ApplicationContext>(options =>
                    options.UseSqlite(hostContext.Configuration.GetConnectionString("DefaultConnection")));
            });
}
using Microsoft.EntityFrameworkCore;

public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options)
    {
    }
    
    public DbSet<Post> Posts { get; set; }
}

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class Post
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
}
using Microsoft.EntityFrameworkCore;

public static class DbInitializer
{
    public static void Initialize(ApplicationContext context)
    {
        context.Database.EnsureCreated();

        var entity = context.Model.FindEntityType(typeof(Post));

        if (entity != null)
        {
            var tableName = entity.GetTableName();

            context.Database.ExecuteSqlInterpolated($"DELETE FROM {tableName}");
        }
    }
}
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (1ms) [Parameters=[@p0='?' (Size = 5)], CommandType='Text', CommandTimeout='30']
      DELETE FROM @p0
fail: Program[0]
      An error occurred while seeding the database.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'near "@p0": syntax error'.
   at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
   at Microsoft.Data.Sqlite.SqliteCommand.PrepareAndEnumerateStatements(Stopwatch timer)+MoveNext()
   at Microsoft.Data.Sqlite.SqliteCommand.GetStatements(Stopwatch timer)+MoveNext()
   at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader()
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameter
Object)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(DatabaseFacade databaseFacade, Stri
ng sql, IEnumerable`1 parameters)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(DatabaseFacade databaseFacade, Stri
ng sql, Object[] parameters)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlInterpolated(DatabaseFacade databaseFac
ade, FormattableString sql)
   at DbInitializer.Initialize(ApplicationContext context) in <file>:line 15
   at Program.Main(String[] args) in <file>:line 21

This does not work either:

context.Database.ExecuteSqlRaw("DELETE FROM {0}", tableName);

However this does:

context.Database.ExecuteSqlRaw("DELETE FROM Posts");

Additional context

Microsoft.EntityFramework.Core version: 3.0.0 Microsoft.Data.Sqlite version: 3.0.0 Target framework: .NET Core 3.0 Operating system: Windows 10

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
bricelamcommented, Nov 4, 2019

Use string concatenation. SQLite doesn’t support parameter reference tokens in that part of the SQL.

1reaction
bricelamcommented, Nov 5, 2019

It’s a SQL syntax error. We don’t parse SQL in EF Core or ADO.NET so that super unhelpful error coming directly from SQLite is the best we can do. Their errors are notoriously vague and unhelpful ☹️

Read more comments on GitHub >

github_iconTop Results From Across the Web

DELETE FROM <table name> does not work ...
DELETE FROM <table name> does not work as expected in EF Core when using the Microsoft.Data.Sqlite driver #18747.
Read more >
EF Core: SQLite delete is not cascading
Everything seems to work as it should, except the .Remove() call, which removes the element as expected, but is not cascading to other...
Read more >
Breaking changes included in EF Core 3.x
Complete list of breaking changes introduced in Entity Framework Core 3.x.
Read more >
Breaking changes in EF Core 7.0 (EF7)
This is a severe breaking change in the Microsoft.Data.SqlClient package. There is nothing that can be done in EF Core to revert or...
Read more >
Part 5, work with a database in an ASP.NET Core MVC app
If a migration is created to remove or change a column, the ef migrations add command succeeds but the ef database update command...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found