Trouble Determining Dependent Side in One-to-One Relationship with Entity Framework Core

I'm currently working on a project using Entity Framework Core in a .NET Core application. I'm having trouble determining the dependent side in a one-to-one relationship between the User and Account entities. I tried configuring the entities and their relationships according to the established standards, but I'm encountering an error:

The dependent side could not be determined for the one-to-one relationship between 'Account.User' and 'User.Account'. To identify the dependent side of the relationship, configure the foreign key property...

My configuration classes look like this:

public class User : BaseModel
{
    public Account Account { get; set; }
    public int AccountId { get; set; }
}

public class Account : BaseModel
{
    public User User { get; set; }
    public int UserId { get; set; }
}

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasOne(u => u.Account)
            .WithOne(a => a.User)
            .HasForeignKey<Account>(a => a.UserId);
    }
}

public class AccountConfiguration : IEntityTypeConfiguration<Account>
{
    public void Configure(EntityTypeBuilder<Account> builder)
    {
        builder.HasOne(a => a.User)
            .WithOne(u => u.Account);
    }
}

SQL to create tables:

CREATE TABLE [dbo].[Accounts] 
(
    [Id] INT IDENTITY (1, 1) NOT NULL,
    [UserId] INT NOT NULL,

    CONSTRAINT [PK_Accounts] 
        PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_Accounts_Users] 
        FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([Id]) 
            ON DELETE CASCADE
);
GO

CREATE INDEX [IX_Accounts_UserId] 
ON [dbo].[Accounts] ([UserId]);

CREATE TABLE [dbo].[Users] 
(
    [Id] INT IDENTITY (1, 1) NOT NULL,
    [AccountId] INT NULL, -- This can be NULL if we set the FK on the Account table

    CONSTRAINT [PK_Users] 
        PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_Users_Accounts] 
        FOREIGN KEY ([AccountId]) REFERENCES [dbo].[Accounts] ([Id]) 
            ON DELETE NO ACTION
);
GO

CREATE INDEX [IX_Users_AccountId] 
ON [dbo].[Users] ([AccountId]);

Upvotes: 0

Views: 64

Answers (0)

Related Questions