Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configure PrincipleToDependent property in one-to-one relationship #35771

Open
sjb-sjb opened this issue Mar 12, 2025 · 0 comments
Open

Configure PrincipleToDependent property in one-to-one relationship #35771

sjb-sjb opened this issue Mar 12, 2025 · 0 comments

Comments

@sjb-sjb
Copy link

sjb-sjb commented Mar 12, 2025

Question

I have entities TreeContent and TreePoint that are to be in a one-to-one relationship, in simplified form:

public abstract class TreeContent
{
    int CGPK { get; set; } // primary key, not called "Id"

    public TreePoint? TreePoint { 
        get => this._treePoint;
        set => this._treePoint = value;
    }
    private TreePoint? _treePoint; 
}

public class TreePoint {
    int CGPK { get; set; } // primary key

    public TreeContent TreeContent {
        get => this._treeContent ?? throw new InvalidOperationException();
        set => this._treeContent = value; 
    }
    private TreeContent? _treeContent;
}

It is the TreePoint that is the principle entity and the TreeContent that is the dependent (the nullability is opposite this, I know, but that is due to other reasons. I'm also using a nonstandard name for the primary key.)

I then configure the one-to-one relationship using modelBuilder.Entity<TreePoint>().HasOne( tp => tp.TreeContent).WithOne( tc => tc.TreePoint).HasForeignKey<TreeContent>( nameof(TreePoint)+"CGPK");

At run time I inspect the model and find the foreign key. It has DependentToPrincipal set correctly to be the treeContent.TreePoint property. However, the PrincipleToDependent property is null. (The generated model also does not contain a foreign key in the TreePoint referring back to the TreeContent.)

What am I missing?? I don't see how to configure the property of the principle entity that refers back to the dependent entity. I need PrincipalToDependent in the foreign key to address some validation requirements.

EF Core version

9.0.1

Database provider

Microsoft.EntityFrameworkCore.Sqlite

Target framework

No response

Operating system

No response

IDE

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant