如何访问并获取其他课程的财产?

时间:2014-05-10 14:55:52

标签: c# wpf mvvm

我有一个应用 WPF MVVM ,允许员工创建一个或多个项目,每个项目属于员工所以我的问题是: 当我添加员工时,我还想添加一个项目,以便项目接收 员工 ID ,以便我可以识别关系员工和项目之间。这是一个例子:

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

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

这是我的代码:

员工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"/>

2 个答案:

答案 0 :(得分:2)

这一切都取决于你如何存储它等等。如果它存储在关系数据库中,那么最简单的事情就是创建外键,这将是一对多关系,其中一个Employee有多个项目,但每个项目只有一个所有者(Employee)。然后在代码中你必须拥有反映这种关系的属性,例如项目将具有EmployeeId属性,而Employee将具有项目ID列表作为属性。如果您不想更改您的课程,也可以使用单独的表格/对象来存储关系。

答案 1 :(得分:0)

看起来像一个简单的问题需要解决。

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" }
}};