使用实体框架核心的Xamarin.iOS在真实设备系统上.typeinitializationException

时间:2019-01-17 22:37:38

标签: xamarin xamarin.forms xamarin.ios .net-core entity-framework-core

引用此帖子:Xamarin iOS Linker Issue

我遇到了同样的问题。这是在此代码上抛出的异常(突出显示了一行):

using (var scope = ServiceProvider.CreateScope())
{
  var dbContextLocal = 
        scope.ServiceProvider.GetRequiredService<C4S_DataContext>();
  dbContextLocal.Database.EnsureCreated(); //Exception occurs here

  if (!dbContextLocal.Kontakte.Any())
  {
      var settingsViewModel = new SettingsViewModel(dbContextLocal);
      settingsViewModel.SyncDatabasesCommand.Execute(null);
  }
}

例外:

system.typeinitializationexception: The type initializer for 'Microsoft.EntityFrameworkCore.Sqlite.Query.ExpressionTranslators.Internal.Sql iteCompositeMethodCallTranslator' threw an exception.

我尝试了建议的解决方案,但不幸的是它没有解决我的问题。

我的配置

EF Core版本:v2.2.1 数据库提供程序:Microsoft.EntityFrameworkCore.Sqlite 作业系统:Windows 10 / iOS 12.1.2 IDE:Visual Studio 2017(15.9.5)

感谢您的帮助!

编辑:

这是建立依赖项注入的ServiceProvider的代码:

        //Services für Dependency Injection 
    public void RegisterServices(IServiceCollection services)
    {
        // Register services here.
        services.AddEntityFrameworkSqlite();

        services.AddDbContext<C4S_DataContext>(options =>
    options.UseSqlite($"Filename={_dbPath}"));

        services.AddTransient<PortfolioGruppenViewModel>();
        services.AddTransient<PortfolioElementeViewModel>();
        services.AddTransient<RegionenViewModel>();
        services.AddTransient<KontakteGroupViewModel>();
        services.AddTransient<KontaktDetailsViewModel>();

        services.AddTransient<SettingsViewModel>();

        ServiceProvider = services.BuildServiceProvider();

        using (var scope = ServiceProvider.CreateScope())
        {
            var dbContextLocal = scope.ServiceProvider.GetRequiredService<C4S_DataContext>();
            dbContextLocal.Database.EnsureCreated();

            if (!dbContextLocal.Kontakte.Any())
            {
                var settingsViewModel = new SettingsViewModel(dbContextLocal);
                settingsViewModel.SyncDatabasesCommand.Execute(null);
            }
        }
    }

在SecureCreated()上发生异常。

1 个答案:

答案 0 :(得分:1)

我可以在Xamarin支持团队的帮助下解决我的问题。

将以下LinkDescription.xml文件添加到Xamarin.iOS项目中,并将其构建操作设置为LinkDescription:

<?xml version="1.0" encoding="UTF-8" ?>
<linker>
    <assembly fullname="mscorlib">
         <type fullname="System.DateTime" preserve="methods" />
    </assembly>
</linker>

来源:https://github.com/xamarin/xamarin-android/issues/2620