efcore icon indicating copy to clipboard operation
efcore copied to clipboard

NuGet Commands: BadImageFormatException while trying to load sqlite3.dll

Open cgideon opened this issue 11 years ago • 9 comments

I'm not sure if this is the right place to ask this, if it's not please accept my apologies.

I'm working on an application where I need to have a composite key in two different tables, one would be primary the second would be a foreign key in an SQLite database. There seems to be an issue with creating composite keys in both the Fluent API and using annotations like in earlier EF versions. With annotations I get the below error:

System.InvalidOperationException: Entity type 'Device' has composite primary key defined with data annotations. To set composite primary key, use fluent API.

But when I use the Fluent API and do something like

    modelBuilder.Entity<Device>().HasKey(d => new { d.DeviceType, d.DeviceIdentifier });

I get this error when running Update-Database via the Package Manager Console:

PM> Update-Database System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(IntPtr filename, Sqlite3Handle& ppDb, Int32 flags, IntPtr vfs) at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(String filename, Sqlite3Handle& ppDb, Int32 flags, String vfs) at Microsoft.Data.Sqlite.SqliteConnection.Open() at Microsoft.Data.Entity.Storage.RelationalConnection.Open() at Microsoft.Data.Entity.Storage.Internal.SqliteRelationalConnection.Open() at Microsoft.Data.Entity.Storage.SqlStatementExecutor.Execute[T](IRelationalConnection connection, RelationalCommand command, Func`2 action) at Microsoft.Data.Entity.Storage.SqlStatementExecutor.ExecuteScalar(IRelationalConnection connection, String sql) at Microsoft.Data.Entity.Migrations.HistoryRepository.Exists() at Microsoft.Data.Entity.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.Data.Entity.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) at Microsoft.Data.Entity.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType) at Microsoft.Data.Entity.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.Execute(Action action) An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

I put together a quick PoC project which can be found here: https://github.com/cgideon/CSharpEntityFramework7

The versions of EF7 I'm using are EntityFramework.Sqlite 7.0.0-Beta8 and EntityFramework.Commands 7.0.0-Beta8 and SQLite version 3.9.2 64-bit. I'm not sure if this something wrong with my implementation or if it's just not a supported feature yet.

Thanks!

cgideon avatar Nov 11 '15 14:11 cgideon

Full code:

public class Device
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        public string DeviceType { get; set; }
        public UInt32 DeviceIdentifier { get; set; }

        public List<DeviceConfiguration> DeviceConfiguration { get; set; } 
    }

    public class DeviceConfiguration
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        public string DeviceType { get; set; }
        public UInt32 DeviceIdentifier { get; set; }
        public string Description { get; set; }
        public string DateTime { get; set; }
        public string Configuration { get; set; }

        public List<Device> Device { get; set; } 
    }

    public class DeviceContext : DbContext
    {
        public DbSet<Device> Devices { get; set; }
        public DbSet<DeviceConfiguration> DeviceConfigurations { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string databaseFilePath = "Example.db";
            try
            {
                databaseFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), databaseFilePath);
            }
            catch (InvalidOperationException) { }

            optionsBuilder.UseSqlite($"Data source={databaseFilePath}");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Device>().HasKey(d => new { d.DeviceType, d.DeviceIdentifier });
            modelBuilder.Entity<Device>().Property(d => d.DeviceType).IsRequired();
            modelBuilder.Entity<Device>().Property(d => d.DeviceIdentifier).IsRequired();

            modelBuilder.Entity<DeviceConfiguration>().HasKey(d => new { d.DeviceType, d.DeviceIdentifier });
            modelBuilder.Entity<DeviceConfiguration>().Property(d => d.DeviceType).IsRequired();
            modelBuilder.Entity<DeviceConfiguration>().Property(d => d.DeviceIdentifier).IsRequired();
            modelBuilder.Entity<DeviceConfiguration>().Property(d => d.Description).IsRequired();
            modelBuilder.Entity<DeviceConfiguration>().Property(d => d.DateTime).IsRequired();
            modelBuilder.Entity<DeviceConfiguration>().Property(d => d.Configuration).IsRequired();
        }
    }

private static void Main(string[] args)
        {
            using (var db = new DeviceContext())
            {
                Device device = new Device
                {
                    DeviceIdentifier = 12,
                    DeviceType = "Device 1",
                    DeviceConfiguration = null
                };

                DeviceConfiguration config = new DeviceConfiguration
                {
                    Configuration = "Test",
                    DateTime = "11/11/15",
                    Description = "A Test Config",
                    Device = { device },
                    DeviceIdentifier = device.DeviceIdentifier,
                    DeviceType = device.DeviceType
                };

                device.DeviceConfiguration = new List<DeviceConfiguration>() { config };

                Console.WriteLine("Inserting Data...");

                db.Devices.Add(device);
                db.SaveChanges();

                db.DeviceConfigurations.Add(config);
                db.SaveChanges();

                Console.WriteLine("Selecting data from the Database");

                foreach (var d in db.Devices)
                {
                    Console.WriteLine("Device ID: " + d.Id);
                    Console.WriteLine("Device Identifier: " + d.DeviceIdentifier);
                    Console.WriteLine("Device Type: " + d.DeviceType);
                    foreach (var c in d.DeviceConfiguration)
                    {
                        Console.WriteLine("Device Configuration: " + c.Configuration);
                        Console.WriteLine("Device Configuration Date Time: " + c.DateTime);
                        Console.WriteLine("Device Configuration Device Identifier: " + c.DeviceIdentifier);
                        Console.WriteLine("Device Configuration Device Type: " + c.DeviceType);
                        Console.WriteLine("Device Configuration Id: " + c.Id);
                    }
                }

                Console.WriteLine("Examples run finished,press Enter to continue...");
                Console.ReadLine();
            }
        }

cgideon avatar Nov 11 '15 14:11 cgideon

Hmm, we made a lot of improvements to our SQLite native library loading in RC1. Could you try again using the nightly builds of RC1? They're available on the aspnetrelease MyGet feed.

bricelam avatar Nov 11 '15 17:11 bricelam

I tried to upgrade to the nightly build version 7.0.0-rc1-16305 and got the below error

Failed to add reference to 'System.Collections.Concurrent'. Please make sure that it is in the Global Assembly Cache.

And running this from Developer Command Prompt for VS2015 throws an error as well

gacutil -i System.Collections.Concurrent.4.0.11-beta-23509.nupkg Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.0 Copyright (c) Microsoft Corporation. All rights reserved.

Failure adding assembly to the cache: The filename, directory name, or volume label syntax is incorrect.

cgideon avatar Nov 11 '15 18:11 cgideon

Remove all nuget packages from references, packages.config and/or project.json, and readd the new packages

ErikEJ avatar Nov 11 '15 19:11 ErikEJ

Thanks @ErikEJ removing all the references allowed me to install the nightly build. I had to also remove the public List<DeviceConfiguration> DeviceConfiguration { get; set; } from my Device model in order for the migration to be created, though I'm not as concerned about that one. Running Update-Database with the new migration I get the same error as before with the NuGet version 7.0.0-Beta8.

System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(IntPtr filename, Sqlite3Handle& ppDb, Int32 flags, IntPtr vfs) at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(String filename, Sqlite3Handle& ppDb, Int32 flags, String vfs) at Microsoft.Data.Sqlite.SqliteConnection.Open() at Microsoft.Data.Entity.Storage.RelationalConnection.Open() at Microsoft.Data.Entity.Storage.Internal.SqliteRelationalConnection.Open() at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnection connection, Func`3 action, String executeMethod, Boolean openConnection, Boolean closeConnection) at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteScalar(IRelationalConnection connection, Boolean manageConnection) at Microsoft.Data.Entity.Migrations.HistoryRepository.Exists() at Microsoft.Data.Entity.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.Data.Entity.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) at Microsoft.Data.Entity.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType) at Microsoft.Data.Entity.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.Execute(Action action) An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Modified code has been checked into my GitHub project.

cgideon avatar Nov 11 '15 19:11 cgideon

Remove you're copy of sqlite3.dll and let the Microsoft.Data.Sqlite package work it's magic.

The issue is that you have an 64-bit version of sqlite3.dll, but the Migrations commands run inside Visual Studio which is a 32-bit process.

If you really need to use a custom/specific version of SQLite, copy the dlls to x86\sqlite3.dll and x64\sqlite3.dll instead of copying the x64 version to the root of the output directory.

bricelam avatar Nov 11 '15 19:11 bricelam

That is exactly what fixed it @bricelam ! I'll go ahead and close this issue, thank you so much for your assistance!

cgideon avatar Nov 11 '15 19:11 cgideon

Note to self: This is an interesting scenario to consider as part of #1074

bricelam avatar Nov 11 '15 19:11 bricelam

You probably already know, but this does work with the 7.0.0-Beta8 release on NuGet as well, not just the nightly build.

Correction:

Unable to get it to work with existing project using the NuGet 7.0.0-Beta8 release. Get this error

System.DllNotFoundException: Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(IntPtr filename, Sqlite3Handle& ppDb, Int32 flags, IntPtr vfs) at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(String filename, Sqlite3Handle& ppDb, Int32 flags, String vfs) at Microsoft.Data.Sqlite.SqliteConnection.Open() at Microsoft.Data.Entity.Storage.RelationalConnection.Open() at Microsoft.Data.Entity.Storage.Internal.SqliteRelationalConnection.Open() at Microsoft.Data.Entity.Storage.SqlStatementExecutor.Execute[T](IRelationalConnection connection, RelationalCommand command, Func`2 action) at Microsoft.Data.Entity.Storage.SqlStatementExecutor.ExecuteScalar(IRelationalConnection connection, String sql) at Microsoft.Data.Entity.Migrations.HistoryRepository.Exists() at Microsoft.Data.Entity.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.Data.Entity.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) at Microsoft.Data.Entity.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType) at Microsoft.Data.Entity.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.Execute(Action action) Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

cgideon avatar Nov 11 '15 19:11 cgideon