I have an example for this done in a console project which will work in an ASP.NET Core project found here.
Self Reference ASP.NET
Guys I am implementing a very basic web application that has ONE Class Only (Employee), however this class should have a Manager(who is also an employee) and they should have one-to-many relationship (1 or Many Employees should have :1 Manager Only, 1 Manager could have more the 1 Employee).
I missed up implementing the Model , the DbContext and the View and now the system is not running and here is what I have done so far:
- The Model:
public class Employee
{
[Key]
[DisplayName("Employee ID")]
public int EmployeeID { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
[DisplayName("First Name")]
[Required]
public string FirstName { get; set; }
public int? ManagerID { get; set; }
public Employee Manager { get; set; }
public ICollection<Employee> ListOfEmployees { get; set; }
}
- DbContext:
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>options):base(options)
{
}
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOne(manager => manager.Manager)
.WithMany(emp => emp.ListOfEmployees)
.HasForeignKey(m => m.ManagerID);
base.OnModelCreating(modelBuilder);
}
}
- The View (Should be a drop down list where you only show the employees related to a manager that you choose from a drop down list):
@model IEnumerable<Employee>
@{
ViewData["Title"] = "Employee List";
}
<label for="Manager">Choose a Manager:</label>
<select name="Manager" id="MangerID">
@foreach(var obj in Model)
{
<option value=@obj.ManagerID>@obj.LastName</option>
}
</select>
- Controller:
//Home Page
public IActionResult Index()
{
var DataSource=_db.Employees.Select(emp => new
{
LastName = emp.LastName,
ManagerName = emp.Manager == null ? "Super Boss" : emp.Manager.LastName
}).ToList();
return View(DataSource);
}
Developer technologies .NET Entity Framework Core
Developer technologies ASP.NET ASP.NET Core
1 answer
Sort by: Most helpful
-
Karen Payne MVP 35,586 Reputation points Volunteer Moderator
2023-03-10T13:39:00.2466667+00:00