Essentials icon indicating copy to clipboard operation
Essentials copied to clipboard

Migration for Xamarin project, unable to use FileSystem

Open ajcvickers opened this issue 7 years ago • 4 comments

Moving this from https://github.com/aspnet/EntityFrameworkCore/issues/15201 filed by @Tristan-gu because the request is for Xamarin to implement a method.


I would like to use Xamarin.essentials.FileSystem to initialize insaide the DBContext class the database Path, and make a migration.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'TestDB.Connect.DataBase.DBContext.DBBaseTestDB' threw an exception. ---> Xamarin.Essentials.NotImplementedInReferenceAssemblyException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
   at Xamarin.Essentials.FileSystem.get_PlatformAppDataDirectory() in D:\a\1\s\Xamarin.Essentials\FileSystem\FileSystem.netstandard.cs:line 12
   at TestDB.Connect.DataBase.DBContext.DBBaseTestDB..cctor() in D:\Xamarin\connect\TestDB.Connect\TestDB.Connect.DataBase\DBContext\Base\DBBaseTestDB.cs:line 22
   --- End of inner exception stack trace ---
   at TestDB.Connect.DataBase.DBContext.DBBaseTestDB..ctor() in D:\Xamarin\connect\TestDB.Connect\TestDB.Connect.DataBase\DBContext\Base\DBBaseTestDB.cs:line 30
   --- End of inner exception stack trace ---
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception has been thrown by the target of an invocation.

Steps to reproduce

I just want to create a DBContext which affects the databasePath automatically with Xamarin.essentials FileSystem.AppDataDirectory. But I have an error when I want to create the first migration with this command Add-Migration InitialCreate

public static readonly string DB_PATH = FileSystem.AppDataDirectory;

Further technical details

EF Core version: latest pre-release Database Provider: Microsoft.EntityFrameworkCore.Sqlite.Core Operating system: Windows IDE: VS 2019

ajcvickers avatar Mar 29 '19 19:03 ajcvickers

From your error it looks like you did not add the NuGet package to your iOS, Android, or UWP project.

Xamarin.Essentials.NotImplementedInReferenceAssemblyException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

jamesmontemagno avatar Mar 30 '19 04:03 jamesmontemagno

Hi @jamesmontemagno , This is impossible for me to add Nuget package to iOS, Android or UWP because I created the dbContext in a library wich uses the xamarin.essentials method.

This is the context code in my .NetStandard library "test.Connect.DataBase":

using System.Collections.Generic;
using System.IO;
using System.Text;
using Xamarin.Essentials;

namespace Test.Connect.DataBase.DBContext
{
    public class ContextTest : DbContext
    {
        public DbSet<ItemBusinessLig> BusinessLignes { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //This works
            //var dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            //This does not work
            var dbPath = FileSystem.AppDataDirectory;

            optionsBuilder.UseSqlite("Data Source=" + Path.Combine(dbPath, "database.db"));
        }
    }
}

And, I created a Console App to create migration with EFCore. When I execute this command:

Add-Migration InitialCreate -StartupProject Test.Connect.DataBase.EFMigration -Context ContextTest -Verbose

I have this error, and I don't know how to resolve it:

PM> Add-Migration InitialCreate -StartupProject Test.Connect.DataBase.EFMigration -Context ContextTest -Verbose
Using project 'Test.Connect.DataBase'.
Using startup project 'Test.Connect.DataBase.EFMigration'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase.EFMigration\bin\Debug\netcoreapp2.1\Test.Connect.DataBase.EFMigration.deps.json --additionalprobingpath C:\Users\pnv_tg.ASP\.nuget\packages --additionalprobingpath C:\ProgramData\Xamarin\NuGet --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase.EFMigration\bin\Debug\netcoreapp2.1\Test.Connect.DataBase.EFMigration.runtimeconfig.json C:\Users\pnv_tg.ASP\.nuget\packages\microsoft.entityframeworkcore.tools\3.0.0-preview3.19153.1\tools\netcoreapp2.0\any\ef.dll migrations add InitialCreate --json --context ContextTest --verbose --no-color --prefix-output --assembly D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase.EFMigration\bin\Debug\netcoreapp2.1\Test.Connect.DataBase.dll --startup-assembly D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase.EFMigration\bin\Debug\netcoreapp2.1\Test.Connect.DataBase.EFMigration.dll --project-dir D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase\ --language C# --working-dir D:\Xamarin\connect --root-namespace Test.Connect.DataBase
Using assembly 'Test.Connect.DataBase'.
Using startup assembly 'Test.Connect.DataBase.EFMigration'.
Using application base 'D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase.EFMigration\bin\Debug\netcoreapp2.1'.
Using working directory 'D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase.EFMigration'.
Using root namespace 'Test.Connect.DataBase'.
Using project directory 'D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'ContextTest'.
Found DbContext 'DBBaseTest'.
Found DbContext 'DBBaseProwin'.
Using context 'ContextTest'.
Xamarin.Essentials.NotImplementedInReferenceAssemblyException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
   at Xamarin.Essentials.FileSystem.get_PlatformAppDataDirectory() in D:\a\1\s\Xamarin.Essentials\FileSystem\FileSystem.netstandard.cs:line 12
   at Test.Connect.DataBase.DBContext.ContextTest.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in D:\Xamarin\connect\Test.Connect\Test.Connect.DataBase\DBContext\Base\ContextTest.cs:line 21
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

Tristan-gu avatar Apr 01 '19 13:04 Tristan-gu

I mean there is no real reason to change the code that you have there. If you already have the database location don't change it. The issue you are running into is because you are running a console application and that isn't supported by Xamarin.Essentials so you are just getting the API.

Xamarin.Essentials File API can be found: https://docs.microsoft.com/xamarin/essentials/file-system-helpers?context=xamarin%2Fxamarin-forms&tabs=android&WT.mc_id=docs-github-jamont

You could do:

var dbPath = string.Emptry;
if(DeviceInfo.Platform == DevicePlatform.Unknown)
    dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
else
    dbPath = FileSystem.AppDataDirectory;

jamesmontemagno avatar Apr 01 '19 20:04 jamesmontemagno

Hi, Thank you very much, this works very well.

Tristan-gu avatar Apr 02 '19 08:04 Tristan-gu