EF Core creates a Shadow FK Index while OnModelCreating and Its causing run time error

I am migrating from Entity Framework to Ef Core and ran into this issue where EF Core is creating a shadow FK Index property and adding 1 at the end as the same-named property already exists in my class.

>  TabCode (decimal) Required Index
>         Annotations: 
>           Relational:ColumnType: decimal(10, 0)
>       TabCode1 (no field, Nullable<decimal>) Shadow FK Index

>  Foreign keys: 
>           PaymentBatch {'ParentPaymentBatchId'} -> PaymentBatch {'PaymentBatchId'} ToDependent: PaymentBatch1 ToPrincipal:
> PaymentBatch2 ClientSetNull
>             Annotations: 
>               Relational:Name: FK_PaymentBatch_PaymentBatch
>           PaymentBatch {'TabCode1'} -> Tab {'TabCode'} ToPrincipal: Tab ClientSetNull
>         Indexes: 
>           ParentPaymentBatchId 
>           TabCode1

The above code is from modelBuilder ToDebugString() result object. I keep getting error saying TabCode1 column doesn’t exist. when I try to run the page. TabCode is the property that has the same name as one of the index. I checked the DB and we have a Non-Clustered index defined which I have defined in OnModelCreating as well. I am not sure what this Shadow FK Index is, and How do I define it in my modelBuilder.

Below is how I am defining my index in modelBuilder

entity.HasIndex(e => new { e.PaymentBatchId, e.TabCode, e.TentType, e.TaxYear }, "TRX_PaymentCodeTentTypeTaxYear")


entity.HasOne<Tab>(d => d.Tab)
                    .WithMany(p => p.PaymentBatch)
                    .HasForeignKey(d => d.TabCode);

The above code fixed my issue. Turns out EF core needs to define any relationship that doesn’t exist in SQL and we were adding a navigational property in our EF.

Leave a Reply

Your email address will not be published. Required fields are marked *