问题保存组合框数据,实体框架

时间:2016-09-28 13:15:33

标签: c# entity-framework combobox

我在保存组合框数据时遇到问题。保存第一时间我没有问题,但是当我使用相同的组合框值再次执行时,我收到以下错误:

  

未处理DbUpdateException 更新条目时发生错误。

private void FillCombo1()
{
    context = new PhonebookEntities();

    comboBox1.DataSource = context.Cities.ToList();
    comboBox1.DisplayMember = "City";
    comboBox1.SelectedIndex = -1;
}
private void FillCombo3()
{
    context = new PhonebookEntities();
    comboBox3.DataSource = context.Firmas.ToList();
    comboBox3.DisplayMember = "Firma";
    //comboBox3.Invalidate();
    comboBox3.SelectedIndex = -1;
}


private void save_Click(object sender, EventArgs e)
{
    context = new PhonebookEntities();
    int new_id;
    if (context.Books.Count() < 1)
    {
        new_id = 1;
    }
    else
    {
        int curr_id = context.Books.Max(b => b.id);
        new_id = curr_id + 1;
    }
    Book newbook = new Book();
    newbook.id_firma = Convert.ToInt32(comboBox3.SelectedIndex.ToString());

    newbook.id      = new_id;
    newbook.name    = name1.Text;
    newbook.phone   = phone1.Text;
    newbook.phone2  = phone2.Text;
    newbook.note    = note.Text;
    context.Books.Add(newbook);
    context.SaveChanges();
    MessageBox.Show("Записът е успешен");
    LoadBook();
}

This is my database schema:

0 个答案:

没有答案