如何获取所选项的值并插入

时间:2016-06-01 12:55:51

标签: c# asp.net entity-framework

我已经制作了这个简单的代码,通过Entity Framework中的Web Form而不是MVC中插入记录。我想从DropdownList enter image description here

中选择所选项目的部门值

以上数据是手动添加到数据库中...如果我从这里插入记录...它正在创建新的数据槽。我希望将其添加到从下拉列表中选择的同一类别中。

代码

public partial class WebForm1 : System.Web.UI.Page
{
    EmployeeDbContext db = new EmployeeDbContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = db.Departments.ToList();
            DropDownList1.DataBind();
        }

        GridView1.DataSource = db.Departments.Include("Employees").ToList();
        GridView1.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Employee emp = new Employee(){Name = TextBox1.Text,
            Gender= TextBox2.Text,
            Salary = float.Parse(TextBox3.Text),

            //this retuns '_Page' in ID.
            Department = 
            new Department() { ID = Convert.ToInt32(DropDownList1.SelectedValue)}
        }; 

        db.Employees.Add(emp);
           db.SaveChanges();
    }
}

public class Department
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public List<Employee> Employees { get; set; }
}

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public float Salary { get; set; }
    public Department Department { get; set; }
}

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

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可以选择Departments已经存在,您应该使用并设置FK属性而不是设置导航属性:

public class Employee
{
    //add this property
    [ForeignKey("Department")]
    public int  DepartmentId { get; set; }
    public Department Department { get; set; }
}

然后在你的代码中你可以这样做:

Employee emp = new Employee(){Name = TextBox1.Text,
                              Gender= TextBox2.Text,
                              Salary = float.Parse(TextBox3.Text),
                              DepartmentId=Convert.ToInt32(DropDownList1.SelectedValue)
                             }; 

 db.Employees.Add(emp);
 db.SaveChanges();

设置该属性是您将当前部门与新员工联系起来所需要做的唯一事情。

更新

现在我看到你在获取部门ID时遇到问题,在这种情况下你可以按照@Mike在答案中推荐的内容,或者你也可以在你的页面中这样做:

<asp:DropDownList ID="DepartmentsDropDownList" runat="server" DataTextField="Name" DataValueField="ID" />