使用Entity Framework更新实体时出错

时间:2016-06-30 13:29:12

标签: entity-framework linq c#-4.0

我有一个学生对象,它与部门对象有多对一的关系。我已将学生对象插入到没有Department对象的数据库中。

我试图通过将Department对象加载到组合框来更新Student对象。当用户点击datagridview中的一行时,我这样做。这是我的代码。

  private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewRow dr = dataGridView1.Rows[e.RowIndex];
        long studentid = (long)dr.Cells[0].Value;

        using(var ctx=new DatabaseFirstEntities())
        {
            var st = ctx.Students.Find(studentid);
            if(st!=null)
            {
                utextstydentname.Text = st.Name;
                upstlastname.Text = st.LastName;
                dateTimePicker3.Value = st.DOB;

                var deparments=ctx.Departments.ToList();



                comboBox1.DataSource = deparments;
                comboBox1.DisplayMember = "DepartmentName";
                comboBox1.ValueMember = "DepartmentName";

                updatestudent = st;
            }
        }
    }

      private void btnUpdate_Click(object sender, EventArgs e)
    {
        using(var ctx=new DatabaseFirstEntities())
        {
            Department d = comboBox1.SelectedItem as Department;

            long did = d.DepartmentId;

            updatestudent.Department = d;
            ctx.Entry(updatestudent).State = EntityState.Modified;
            ctx.SaveChanges();

        }
    }

但是当我点击更新按钮时,我得到以下错误。 {"发生了参照完整性约束违规:' Department.DepartmentId'的属性值。在一段关系的一端与'Student.DepartmentId'的属性值不匹配。在另一端。"}

请帮忙。

  public partial class Student
{
    public long StudentId { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public System.DateTime DOB { get; set; }
    public Nullable<long> DepartmentId { get; set; }

    public virtual Department Department { get; set; }
}



public partial class Department
{
    public Department()
    {
        this.Students = new HashSet<Student>();
        this.Teachers = new HashSet<Teacher>();
    }

    public long DepartmentId { get; set; }
    public string DepartmentName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
    public virtual ICollection<Teacher> Teachers { get; set; }
}

}

enter image description here

您的建议确实奏效了。但这是正确的方法吗?

因为我可以像这样创建实体。

     Department d = new Department { DepartmentName = "Psychology" };
        Student st=new Student(){ Name="Student4",LastName="",DOB=DateTime.Now,Department=d};

        var ctx = new DatabaseFirstEntities();
        ctx.Students.Add(st);
        ctx.SaveChanges();

那么,如果我想更新,为什么我不能使用导航属性?

感谢您的帮助。

0 个答案:

没有答案