0

質問内容

Microsoft Docs(Entity Framework > Azure Cosmos DB プロバイダー)を参考にし、ネストした構造のデータを挿入しようとしたところ、エラーが発生しました。

何が原因で発生したエラーなのかについて教えてください。

詳細

Entity Framework Sample (Cosmos DB) を参考にしつつ、Cosmos DBに以下のようなデータを入れたいと考えています。

{
    "Id": 1,
    "id": "1",
    "Address": {
        "ShipsToCity": "London",
        "ShipsToStreet": "221 B Baker St"
        "Test": {
            "Name": "John Doe"
        }
    }
}

そこで、下記のような変更を行いました。

//StreetAddress.cs
namespace Cosmos.ModelBuilding
{
    #region StreetAddress
    public class StreetAddress
    {
        public string Street { get; set; }
        public string City { get; set; }
        public TestClass Test { get; set; }
    }
    #endregion

    public class TestClass
    {
        public string Name { get; set; }
    }
}
//OrderContext.cs
namespace Cosmos.ModelBuilding
{
    public class OrderContext : DbContext
    {
        ...
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            ...

            #region PropertyNames
            modelBuilder.Entity<Order>().OwnsOne(
                o => o.ShippingAddress,
                sa =>
                {
                    sa.ToJsonProperty("Address");
                    sa.Property(p => p.Street).ToJsonProperty("ShipsToStreet");
                    sa.Property(p => p.City).ToJsonProperty("ShipsToCity");
                    sa.Property(p => p.Test).ToJsonProperty("PostCode");
                });
            #endregion

            ...
        }
    }
}
// Sample.cs
namespace Cosmos.ModelBuilding
{
    public static class Sample
    {
        public static async Task Run()
        {
            ...

            using (var context = new OrderContext())
            {
                await context.Database.EnsureDeletedAsync();
                await context.Database.EnsureCreatedAsync();

                context.Add(new Order
                {
                    Id = 1,
                    ShippingAddress = new StreetAddress { City = "London", Street = "221 B Baker St", Test = new TestClass() { Name = "John Doe" } },
                    PartitionKey = "1"
                });

                await context.SaveChangesAsync();
            }

            ...
        }
    }
}

上記を実行すると、以下のようなエラーとなります。

System.InvalidOperationException
  HResult=0x80131509
  Message=The property 'Order.ShippingAddress#StreetAddress.Test' is of type 'TestClass' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
  Source=Microsoft.EntityFrameworkCore
  スタック トレース:
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidatePropertyMapping(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Cosmos.Internal.CosmosModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.ValidatingConvention.ProcessModelFinalized(IConventionModelBuilder modelBuilder, IConventionContext`1 context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
   at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_Dependencies()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureDeletedAsync(CancellationToken cancellationToken)
   at Cosmos.ModelBuilding.Sample.<Run>d__0.MoveNext() in C:\Users\ower\Desktop\EntityFramework.Docs-master\samples\core\Cosmos\ModelBuilding\Sample.cs:line 20
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Cosmos.Program.<Main>d__0.MoveNext() in C:\Users\ower\Desktop\EntityFramework.Docs-master\samples\core\Cosmos\Program.cs:line 9

  この例外は、最初にこの呼び出し履歴 
    [外部コード]
    Cosmos.ModelBuilding.Sample.Run() (Sample.cs 内)
    [外部コード]
    Cosmos.Program.Main() (Program.cs 内) でスローされました

このエラーを解消したいのですが、エラー内容が何を言わんとしているのか理解できていません。
そこで、下記2点を質問させてください。

  1. このエラーは何故発生するのでしょうか?
  2. エラーを解消するためのヒントがあれば教えてください

よろしくお願いいたします

8
  • まずエラーメッセージの一番下を見ると、参考にしたサンプルプロジェクトで例外が発生しているように見えます。スタートアッププロジェクト(ソリューションエクスプローラーでプロジェクト名が太字になっているもの)の変更を行っていないのでは? 変化は無いかもしれませんが確認してみてください。あるいは別プロジェクトを作ったのではなくソースファイルやクラスだけ追加したとか。それだと切り分けが面倒になるかもしれませんね。
    – kunif
    2020年4月19日 1:37
  • @kunif さん、コメントありがとうございます。スタートアッププロジェクトは Cosmos にした上で、サンプルコードは正常に動作しました。今回のコードを追加すると、上記のエラーになります。変更点はこちらです(もしよろしければ変更点だけでも何か誤った箇所がないかチェックいただけないでしょうか)→ github.com/hydrangeas/EntityFramework.Docs/commit/… 2020年4月19日 2:20
  • この記事あたりかも? ネストした形にしたいならクラス定義もネストさせるとか? Entity Framework - Nested Entity Types 独立したクラスならvirtual ICollection< >で定義するとかでしょうか? あるいはICollectionは必要なくvirtualだけで良いのかも? Entity Framework 6, eager loading nested relationship returns empty collection まあ知識があるわけでは無いのでトンチンカンなことを言っているかもしれませんが。
    – kunif
    2020年4月19日 3:13
  • @kunif さん、情報をありがとうございます。virtual ICollection<> だと、テーブル同士の関係を示すことになるのかな?という理解でした。ICollection を使わない場合だと、実体はどこにいる感じでしょうか・・?とりあえず、public virtual TestClass Test { get; set; } みたいな感じで試行錯誤してみましたが、System.InvalidOperationException: 'The property 'Order.ShippingAddress#StreetAddress.Test' is of type 'TestClass' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'と怒られてしまいました。申し訳ありません。 2020年4月19日 3:35
  • メッセージに従ってTestClassに[NotMapped]を付けるとか、あとはsa.Property(p => p.Test).ToJsonProperty("PostCode");の行のどこかに.Nameを入れてみるとかでしょうか。
    – kunif
    2020年4月19日 4:18

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。