C#和实体框架对象

时间:2012-01-04 14:41:56

标签: c# entity-framework-4

尝试用vs2010和实体框架制作我的第一个c#程序。 这是代码:

public partial class Form1 : Form
{
    ValinorEntities ve = new ValinorEntities();

    public Form1()
    {
        InitializeComponent();

        comboBox1.DataSource = ve.item_groups;
        comboBox1.DisplayMember = "item_group_name";
        comboBox1.ValueMember = "item_group_id";

        var departmentQuery = from d in ve.items
                              from g in ve.item_groups
                              where d.item_group_id_fk == g.item_group_id
                              select new { d.item_name, g.item_group_name, d.item_id, d.item_number };

        dataGridView1.DataSource = departmentQuery;
        dataGridView1.Columns[2].Visible = false;
        dataGridView1.Columns[3].Visible = false;
    }

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
        textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
        textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();

        comboBox1.DataSource = ve.item_groups;
        comboBox1.DisplayMember = "item_group_name";
        comboBox1.ValueMember = "item_group_id";
    }

    private void btn_New_Click(object sender, EventArgs e)
    {
        try
        {
            item item = new Valinor.item();

            item.item_name = textBox1.Text;
            item.item_number = textBox2.Text;
            item.item_group_id_fk = (int)comboBox1.SelectedValue;
            ve.AddToitems(item);
            ve.SaveChanges();

            MessageBox.Show("Insert successful");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Insert failed" + ex);
        }
    }

    private void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            var id = Convert.ToInt32(textBox3.Text);
            item c = ve.items.FirstOrDefault(i => i.item_id == id);

            c.item_name = textBox1.Text;
            c.item_number = textBox2.Text;
            c.item_group_id_fk = (int)comboBox1.SelectedValue;                
            ve.SaveChanges();

            MessageBox.Show("Save successful");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Save failed" + ex);
        }
    }
}

它有效但我有一些问题。

  • 单击一个单元格后,我应该选择comboBox1.SelectedValue到正确的项目?
  • btnSave_Click函数中,textbox3的值引用ID,这不是一个非常优雅的解决方案。我该如何反对取代呢?

  • 如果我知道这些引用,例如:

    textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(); textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();

可以某种方式避免。 要做到这一点,不过zakell dataGridView1_CellMouseClickfügvénynél不会引用单元格的值而是引用对象。这可以解决它吗?

0 个答案:

没有答案