C#C
C#3y ago
22 replies
Joellao

✅ Database Scaffolding going wrong.

Hello all, reading the title you can imagine what I want to ask today. Using efcore to add migrations and scaffold the tables.
I have this relationship

public class UserEntity : IdentityUser<int> {
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Bio { get; set; } = string.Empty;
    public IEnumerable<PostEntity> Posts { get; set; }
    public IEnumerable<GroupEntity> CreatedGroups { get; set; }
    public IEnumerable<GroupEntity> ParticipatingGroups { get; set; }
}

public class GroupEntity{
    [Key]
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public int CreatorId { get; set; }
    public UserEntity Creator { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool IsPrivate { get; set; }
    public IEnumerable<UserEntity> Members { get; set; }
}

public class UserGroupEntity {
    [Key]
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public int CreatorId { get; set; }
    public UserEntity Creator { get; set; }
    public int UserId { get; set; }
    public UserEntity User { get; set; }
    public int GroupId{ get; set; }
    public GroupEntity Group { get; set; }
}

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder
            .Entity<GroupEntity>()
            .HasOne(p => p.Creator)
            .WithMany(u => u.CreatedGroups)
            .HasForeignKey(p => p.CreatorId);

        modelBuilder
            .Entity<GroupEntity>()
            .HasMany(e => e.Members)
            .WithMany(e => e.ParticipatingGroups)
            .UsingEntity<UserGroupEntity>();
    }
Was this page helpful?