我是Entity框架的新手,我有一个愚蠢的问题!
我用数据填充数据网格视图然后进行更改,最后按一个按钮保存更改。 至于我只是应用相同的操作,例如我只是添加新记录,将数据保存到db没有问题。但是当我混合操作时,例如当我添加新记录和连续删除另一个时,然后按下保存按钮,更改将丢失,两个操作都不会在db。上完成。
在按钮点击事件中我只有ctx.SaveChanges()
;在try catch块!
怎么了?
Entity框架是否具有类似会话或每个操作都会发生变化的内容?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HiClinic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
HiClinicEntities ctx = new HiClinicEntities();
private void Form1_Load(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
bs.DataSource = (from r in ctx.People select r).ToList();
bs.AddingNew += new AddingNewEventHandler(personBindingSource_AddingNew);
bs.AllowNew = true;
dataGridView1.DataSource = bs;
}
void personBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
var p = new Person();
ctx.People.Add(p);
e.NewObject = p;
}
private void button2_Click(object sender, EventArgs e)
{
try
{
ctx.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
private void dataGridView1_UserDeletingRow(object sender,DataGridViewRowCancelEventArgs e)
{
var p = long.Parse(e.Row.Cells["PersonID"].FormattedValue.ToString());
ctx.People.Remove(ctx.People.First<Person>(c=>c.PersonID == p));
}
}
}