Try our conversational search powered by Generative AI!

What is wrong with my one-to-one EF Core relationship setup?

Vote:
 
I am attempting to convert an Optimizely CMS ASP.NET 4.x application to CMS12.

I have two related EF Core entities:

public class ScholarshipApplication
{
    public virtual AppUser User { get; set; }

    ...
}
public class AppUser
{
    public virtual ScholarshipApplication ScholarshipApplication { get; set; }

    ...
}

I believe this is a required one-to-one relationship with a shadow foreign key.

Note: I am currently unable to change the model in a way that affects the database.

When I run the application, I get the following error message:

InvalidOperationException: The dependent side could not be determined for the one-to-one relationship between 'AppUser.ScholarshipApplication' and 'ScholarshipApplication.User'. To identify the dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship, configure them independently via separate method chains in 'OnModelCreating'. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.

Here is my OnModelCreating method:

public class ApplicationDbContext : ApplicationDbContext<AppUser>
{
    ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AppUser>()
            .HasOne(a => a.ScholarshipApplication)
            .WithOne(a => a.User)
            .HasForeignKey<ScholarshipApplication>("User_Id");
    }
}

I have verified that the shadow field in the ScholarshipApplication table is named "User_Id" from the legacy database. There is no field in the model that corresponds to this, which is why I assume it is a shadow foreign key.

I've tried every permutation that I could think of using this link as a guide:

One-to-One Relationships (Microsoft)

All of them produce the same error.

Strangely enough, if I refresh the page after the error appears, the site loads normally. If I try to login to the backend (this is an Optimizely CMS), I get the error again and I can't proceed.

I posted this question on Stack Overflow and got this response:

"With a plain-old DbContext, that registration should work. I suspect the problem will like possibly with your base DbContext class: ApplicationDbContext<AppUser> and something it may be trying to configure. I created a simple example with two classes and a shadow FK and it worked just fine. Your base class may be blasting the configureation needed for the relationship."

I believe the base class is controlled by Optimizely.

What am I doing wrong?

#313166
Nov 27, 2023 13:50
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.