-2

I have two tables called employee and team. I want to set relationships among the tables as follows.

  1. employee belongs to a team. (1: m relationship).

  2. team has a team leader (team leader is also an employee). (1:1 relationship)

    employee table

    [primary key]
    public int RegistrationNumber { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }

    team table

    [primary key]
    public string Name { get; set; }
    public string Description { get; set; }


    How can I do it?

1 Answers1

0

Below is a work demo, you can refer to it.

team.cs:

 public class team
        {
            private TeamLeaderDbContext Context { get; set; }
            [Key]
            public string Name { get; set; }
            public string Description { get; set; }
            public int? leaderID { get; set; }
            public employee leader { get { return Context.employees.Find(leaderID); } }
            public ICollection<employee> employees { get; set; }
        }

employee.cs:

public class employee
    {
        [Key]
        public int RegistrationNumber { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

TeamLeaderDbContext:

public class TeamLeaderDbContext : DbContext
    {
        public TeamLeaderDbContext(DbContextOptions<TeamLeaderDbContext> options)
             : base(options)
        {
        }

        public DbSet<team> teams { get; set; }
        public DbSet<employee> employees { get; set; }
    }

homecontroller:

public class HomeController : Controller
    {
        private readonly TeamLeaderDbContext _context;

        public HomeController(TeamLeaderDbContext context)
        {
            _context = context;
        }


        public IActionResult Index()
        {
            var team = _context.teams.Include(c => c.employees).ToList();
            return View();
        }
}

result:

enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10