简体   繁体   English

使用Entity Framework 4更新实体

[英]Updating an entity with Entity Framework 4

Here is the code I'm using to create a new Student. 这是我用来创建新学生的代码。

public class StudentRepository
{
    SchoolEntities db = new SchoolEntities();

    public IQueryable<Student> FindAllStudents()
    {
        return db.Students;
    }

    public Student FindStudent(int id)
    {
        return db.Students.SingleOrDefault(c => c.ID == id);
    }

    public void Add(Student Student)
    {
        db.AddToStudents(Student);
    }

    public void Save()
    {
        db.SaveChanges();
    }
}

Here's how I'm using it: 这是我的使用方式:

private void SaveInformation()
{
    Student student = new Student();
    Int64 gradeId = Convert.ToInt64(cmbGradeParalelo.SelectedValue);
    student.IDGrade = gradeId;
    student.RUDE = Convert.ToInt64(txtRude.Text);

    /*Parents information.*/
    student.FatherName = txtNombrePadre.Text;
    student.FatherProfession = txtProfesionPadre.Text;
    student.MobilePhoneFather = FormatPhoneNumber(txtCelularPadre.Text);
    student.PlaceofWorkFather = txtLugarDeTrabajoPadre.Text;

    student.MotherName = txtNombreMadre.Text;
    student.MotherProfession = txtProfesionMadre.Text;
    student.MobilePhoneMother = FormatPhoneNumber(txtCelularMadre.Text);
    student.PlaceofWorkMother = txtLugarDeTrabajoMadre.Text;

    /*Student information*/
    student.Name = txtNombre.Text;
    student.FatherLastName = txtApellidoPaterno.Text;
    student.MotherLasteName = txtApellidoMaterno.Text;
    student.DateOfBirth = dtpFechaNacimiento.Value.ToShortDateString();
    student.PlaceOfBirth = txtLugarNacimiento.Text;
    student.Sex = sexoMasculino.Checked ? sexoMasculino.Text : sexoFemenino.Text;
    student.Telephone = FormatPhoneNumber(txtTelefono.Text);
    student.MobilePhone = FormatPhoneNumber(txtCelular.Text);
    student.Address = txtDireccion.Text;
    student.Carnet = FormatPhoneNumber(txtCarnet.Text);
    student.Observations = txtObservaciones.Text;

    StudentRepository repo = new StudentRepository();
    repo.Add(student);
    repo.Save();
    MessageBox.Show("Se guardo el registro exitosamente.",
        "Exito!",
        MessageBoxButtons.OK,
        MessageBoxIcon.Information,
        MessageBoxDefaultButton.Button1);
    ClearForm();
}

The problem is when I load the information on a form, and hit the save again, a new Student is created. 问题是当我将信息加载到表单上并再次单击保存时,将创建一个新的Student。 I'd like to modify the students information. 我想修改学生信息。

Any suggestions? 有什么建议么?

You're creating a new Student instance yourself whenever you click save. 单击保存时,您将自己创建一个新的Student实例。 That's correct if you want to create a new Student record, but if you want to edit an existing record, you will have to modify a Student record that you've retrieved from the database instead. 如果要创建新的Student记录,这是正确的,但是如果您要编辑现有记录,则必须修改从数据库中检索到的Student记录。

A better OO approach would be to have the calling form pass the Student object to your student editor form. 更好的OO方法是让调用表单将Student对象传递给学生编辑器表单。 This way, the calling form would instantiate a new Student object itself if creating a new one, then if the DialogResult of the form is OK , add it to the context and save it. 这样,如果创建一个新的Student对象,则调用窗体将实例化一个新的Student对象,然后,如果该窗体的DialogResult OK ,则将其添加到上下文中并保存。 In the case of opening an existing record, the calling form would pass the existing Student record to the editor, then call Save() once it closes. 在打开现有记录的情况下,调用表单会将现有的Student记录传递给编辑器,然后在关闭时调用Save()

On an unrelated note, you really need to Dispose of the context once you're done with it. 无关紧要的是,您确实需要在Dispose完上下文后立即Dispose它。

The easiest solution would be to get the Student first, then make the changes. 最简单的解决方案是首先获取学生,然后进行更改。

var existingStudent = StudentRepository.FindStudent(1); // object now in EF graph
student.RUDE = Convert.ToInt64(txtRude.Text); // object now set to EntityState.Modified
// other fields
repo.Save(); // object saved to database

On a side note, don't do this: 附带说明,不要这样做:

db.AddToStudents(Student);

The recommended way in EF4 is: EF4中推荐的方法是:

db.Students.AddObject(Student);

By the looks of the code, i'm guessing this is either a WinForms or WPF app? 从代码的外观来看,我猜这是WinForms还是WPF应用程序? Maybe your better of using a control with EntityDataSource , as opposed to the painstaking task of manually updating the model. 也许与EntityDataSource一起使用控件更好,而不是手动更新模型这一艰巨的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM