Question

I have an application WPF MVVM that allows an employee to create one or more projects and each project belongs to an employee so my question is: When I add an employee I also want to add a project so that the project receives the ID of the employee so that I can identify the relationship between the employee and the project. Here is an example:

Employee (Id = 1) --------> Project (id = 1)
                            Project (id = 2) 
                            Project (id = 3)

Employee (Id = 2) --------> Project (id = 4) 
                            Project (id = 5) 
                            Project (id = 6)

Here is my code:

Employee ViewModel:

public class EmployeeViewModel
{
    Employee _employee = new Employee();

    private IList<Project> _ListeProject;

    public IList<Project> ListeProject
    { get; set; }

    public void InsetEmployee(Employee Employee)
    {
        context.Employee.Add(Employee);
        context.Entry(Employee).State = EntityState.Added;
        context.SaveChanges();
    }

    private void AddEmployee()
    { InsetEmployee(_employee); }
}

Project ViewModel:

public class ProjectViewModel 
{
    Project _project = new Project();
    ProjectBL _projectBL = new ProjectBL ();

    private void AddProject()
    { _projectBL.InsetProject(_project); }        
}

Employee.xaml:

<telerik:RadButton  Content="Add" Height="23" Name="btnAdd"
    HorizontalAlignment="Stretch" VerticalAlignment="Bottom"
    Width="120" Command="{Binding AddEmployeeCMD}"/>
<telerik:RadButton   Content="Add Project" Height="23"
    HorizontalAlignment="Stretch" VerticalAlignment="Bottom"
    Width="120" Click="Project"/>
Was it helpful?

Solution

It all depends on how You store it and so on. If it is stored in relational database, then easiest thing to do is creat foreing keys, this would be one to many relationship, where one Employee has multiple projects but each project have got only one owner (Employee). And then in code You have to have properties which reflect this relantionship, e.g. Project would have EmployeeId property, and Employee would have list of project ids as a property. You could also use seperate table / object to store relationship if You don't want to change Your classes.

OTHER TIPS

Seems like a simple enough problem to solve.

class Employee
{
    public int Id { get; set; }
    public IEnumerable<Project> Projects { get; set; }
}

class Project
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
}

var employee = new Employee { Id = 1, Projects = new List<Project>
{
    new Project { EmployeeId = 1, Name = "Foo" },
    new Project { EmployeeId = 1, Name = "Bar" }
}};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top