I've got a simple structure in database:
CREATE TABLE user_categories (
user_id INT NOT NULL,
category_id INT NOT NULL,
PRIMARY KEY (user_id, category_id)
);
CREATE TABLE user_defaults (
user_id INT NOT NULL,
category_id INT NOT NULL,
PRIMARY KEY (user_id),
FOREIGN KEY (user_id, category_id) REFERENCES user_categories (user_id, category_id)
);
The intention here is that user has a set of categories assigned and there's a table with defaults table (which could potentially have other columns)
However I struggle to map this to EF Core, I always end up getting extra columns in user_categories
table.
My UserCategory
class:
using System.ComponentModel.DataAnnotations.Schema;
namespace EMMA.Authorization.Domain.Entities
{
public class UserCategory
{
public int UserId { get; set; }
[ForeignKey(nameof(UserId))]
public User User { get; set; }
public int CategoryId { get; set; }
[ForeignKey(nameof(CategoryId))]
public Category Category { get; set; }
public UserDefaults UserDefaults { get; set; }
}
}
UserDefaults
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace EMMA.Authorization.Domain.Entities
{
public class UserDefaults
{
public int UserId { get; set; }
public int CategoryId { get; set; }
public virtual ICollection<UserCategory> UserCategories { get; set; }
}
}
That's OnModelCreating
method that should configure relationships:
modelBuilder.Entity<UserCategory>().HasKey(s => new { s.UserId, s.CategoryId });
modelBuilder.Entity<UserDefaults>().HasKey(s => s.UserId);
modelBuilder.Entity<UserDefaults>()
.HasMany(s => s.UserCategories)
.WithOne(s => s.UserDefaults)
.HasForeignKey(s => new { s.UserId, s.CategoryId })
.IsRequired();
However that's the exception I'm getting when I try to create a migration:
The relationship from 'UserCategory.UserDefaults' to 'UserDefaults.UserCategories' with foreign key properties {'UserId' : int, 'CategoryId' : int} cannot target the primary key {'UserId' : int} because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.
How could I configure such an relationship in EF Core as shown in SQL?