使用Entity Framework将更改从WinForms DataGridView更新到数据库

时间:2016-06-24 09:41:54

标签: c# winforms entity-framework datagridview sql-update

我坚持将更改从datagridview更新回db。

这就是我所做的:有没有更好的解决方案?

有没有办法只通过dataSet更新它就像使用sql查询和adapter.Update(ds);

时一样
        BindingSource bs = new BindingSource();
        OkladeNEW2Entities context = new OkladeNEW2Entities();
        IEnumerable<Results> allmlbresults;

        private void button1_Click(object sender, EventArgs e)
        {
            allmlbresults = context.AllMLBResults
            .Where(s => s.StarterHLastName == "Lester")
            .OrderByDescending(o => o.ID)
            .Take(10)
            .Select(t => new Results
            {
                ID = t.ID,
                Team = t.Team,
                StarterHLastName = t.StarterHLastName,
                Opp = t.Opp,
                StarterALastName = t.StarterALastName,
                Final = t.Final
            })
            .ToList();

            bs.DataSource = allmlbresults;
            dataGridView1.DataSource = bs;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                int ID = Convert.ToInt32(row.Cells["ID"].Value);
                if (ID != 0)
                {
                    AllMLBResult results = context.AllMLBResults.FirstOrDefault(r => r.ID == ID);
                    results.ID = Convert.ToInt32(row.Cells["ID"].Value);
                    results.Team = row.Cells["Team"].Value.ToString();
                    results.StarterHLastName = row.Cells["StarterHLastName"].Value.ToString();
                }
            }
            context.SaveChanges();
            //  context.Dispose();
            button1_Click(sender, e);
        }
    }

    internal class Results
    {
        public int ID { get; set; }
        public string Team { get; set; }
        public string StarterHLastName { get; set; }
        public string Opp { get; set; }
        public string StarterALastName { get; set; }
        public string Final { get; set; }
    }

0 个答案:

没有答案