Scenario:
I am implementing Asp.Net MVC project with Entity Framework. I have following entities:
class Employee{
public int Id{get;set;}
[Required]
public string Name{get;set;}
}
class Department{
public int Id{get;set;}
public string DepartmentName{get; set;}
public virtual Employee manager{get; set;}
}
Now, I have to create new department that will have a manager from the list of employees in database. For this, view and controller actions are:
@Html.EditorFor(model => model.DepartmentName)
@Html.DropDownListFor(model => model.manager.Id, new SelectList(ViewBag.Managers, "Id", "Name"))
public class DepartmentController: Controller{
private MyDatabaseContext db = new MyDatabaseContext();
[HttpGet]
public ActionResult Create(){
ViewBag.Managers = db.Employees.ToList();
return View();
}
[HttpPost]
public ActionResult Create(Department d){
if(ModelState.IsValid){
d.manager = db.Employees.Find(d.manager.Id);
db.Departments.Add(d);
db.SaveChanges();
return RedirectToAction("Index");
}
else{
//error response.
//Error encounters as d.manager.Name field would be null.
}
}
}
Problem:
When running above program, I cannot create new Department
's object, as the ModelState.IsValid
is always false
. The reason for this is that the navigation property manager
has field Name
, which would be null
when submitting the form. As Name
is required field, this would be listed as error.
Question:
How can I overcome the error due to null
in field of navigation property? Or, is there other ways to implement this code so that I will get rid of this error?
Notes:
Please make note that I don't want to create different ViewModel
merely useful for creating the Department
object. I would prefer following DRY principle.
Further, I don't want to create different field (something like, managerId
) which would be foreign key to Employees
table because I don't want the database associations taken care on the object oriented models. It's always cleaner to retrieve manager through department.manager
, rather than reading manager object from entity framework by passing the department.managerId
[Key] field.
Thank you.