C#C
C#11mo ago
Adam

✅ [solved] efcore owned entity issue

modelBuilder.Entity<A>(aBuilder =>
        {
            aBuilder.HasKey("Id");
            aBuilder.Property<Guid>("Id");

            aBuilder.OwnsMany<B>(
                "bList",
                bBuilder =>
                {
                    bBuilder.HasKey("Id"); // Without it Ef core sets pair (AId, Id) as key but it is not needed - only one key (Id) is enough
                    bBuilder.Property<Guid>("Id");
                    bBuilder.Property<Guid>("AId").HasColumnName("AId");
                    bBuilder.WithOwner().HasForeignKey("AId");

                    bBuilder.OwnsOne<C>(b => b.C, cBuilder =>
                    {
                        cBuilder.Property<Guid>("Id");
                        cBuilder.Property<Guid>("BId").HasColumnName("BId");
                        cBuilder.WithOwner().HasForeignKey("BId");
                    });
                }
            );
        });

Unable to create a 'DbContext' of type 'DatabaseContext'. The exception 'The keys {'BId'} on 'C' and {'Id'} on 'B' are both mapped to 'B.PK_B', but with different columns ({'BId'} and {'Id'}).' was thrown while attempting to create an instance.
Was this page helpful?