'Set one to one and one to many both relationships among two tables
I have two tables called employee and team. I want to set relationships among the tables as follows.
employee belongs to a team. (1: m relationship).
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?
Solution 1:[1]
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Qing Guo |

