如何在mvc .net中设置两个表之间的关系

时间:2014-10-05 16:50:20

标签: c# mysql sql asp.net-mvc entity-framework

我刚刚开始使用MVC,现在我想设置两个表之间的关系

这是我的员工表

id |名称|薪水| DEPTID

这是我的Deparrtment表

Deptid | DEPTNAME

现在我有一个创建视图来将数据插入我的Employee表

喜欢这个

姓名:..................
薪水:................
Deptid:下载部门列表[但是当我将其保存在表格中时,它应该只保存相应的deptid]

在这里你可以看到我创建的模型

public class Employee
{
    public int id { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public int Deptid { get; set; }
}

这是我的其他模特部门

public class Department
{
    [Key]
    public int Deptid { get; set; }
    public string Deptname { get; set; }
    public List<Employee> Employees { get; set; }
}

我为Dbcontext创建了另一个类

public class Employeecontext:DbContext<br>
{
    public DbSet<Employee>Employees{get;set;}
    public DbSet<Department>Departments{get;set;}
}

如前所述,我有一个创建视图,我将收集数据并将其存储在Employees表中,但有一个标准是在下拉列表中我将有部门名称,但我想保存相应部门的deptid表

提前致谢,如果没有提及或犯过任何错误,我很抱歉,我是新手:P

2 个答案:

答案 0 :(得分:1)

为您的实体类试用以下代码。你的db-context类没问题。我在C#MVC4应用程序中测试了以下模式,没有任何代码优先方法的问题。

public class Department
{

    public Department()
    {
        List<Employee>  EmployeeList = new List<Employee>();
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Deptid { get; set; }
    public string Deptname { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}


public class Employee
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    public string name { get; set; }
    public int Salary { get; set; }
    public int Deptid  { get; set; }

    [ForeignKey("Deptid ")]
    public virtual Department department { get; set; }
}

答案 1 :(得分:1)

您可以这样做:

public class Employee
{
   public int id { get; set; }
   public string Name { get; set; }
   public int Salary { get; set; }
   public int Deptid { get; set; }

   [ForeignKey("Deptid")]
   public virtual Department Department { get; set; }
}

public class Department
{
   [Key]
   public int Deptid { get; set; }
   public string Deptname { get; set; }
}

您不必在您的部门中包含员工列表,因为它只依赖于部门。