Ali Bayat Mokhtari
Ali Bayat Mokhtari

Reputation: 188

Dotnet ef core relations

How can we have a one-to-many relationship when the primary key of all the models named Id?

Example:

public class Organization {
    public long Id { get; set; }
    public List<Teacher> Teachers { get; set; }
}

public class Teacher {
    public long Id { get; set; }
    public long ??? { get; set; } // what do we call OrganizationId?
    public Organization Organization { get; set; }
}

Upvotes: 0

Views: 38

Answers (1)

Todor Vasilev
Todor Vasilev

Reputation: 58

The name of the variable with ??? should be called OrganizationId. I would create a separate class with the configuration for the model Teacher.

For example:

class TeacherConfiguration : IEntityTypeConfiguration<Teacher>
{
    public void Configure(EntityTypeBuilder<BoardCard> builder)
    {
        builder.HasKey(bc => bc.Id);
        builder.HasOne(bc => bc.Organization).WithMany(c => c.Teachers).HasForeignKey(bc => bc.OrganizationId).OnDelete(DeleteBehavior.Cascade).IsRequired();
    }
}

Upvotes: 1

Related Questions