实体类:
[Table(Name = "AA")]
public class ClassDemo
{
[Column(IsPrimaryKey = true, UpdateCheck = UpdateCheck.Never, IsVersion = true)]
public int Id
{
get;
set;
}
[Column]
public string Name
{
get;
set;
}
}
窗体图片:
增 / 删 / 改 / 查 实现方法:
DataContext dc = new DataContext("server=.;database=test;uid=sa;pwd=sa");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Bind();
}
/// <summary>
/// 绑定事件
/// </summary>
public void Bind()
{
Table<ClassDemo> table = dc.GetTable<ClassDemo>();
this.dataGridView1.DataSource = from value in table
orderby value.Id descending
select value;
}
/// <summary>
/// 添加事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Table<ClassDemo> table = dc.GetTable<ClassDemo>();
ClassDemo cd = new ClassDemo();
cd.Name = this.txtName.Text;
table.InsertOnSubmit(cd);
dc.SubmitChanges();
Bind();
}
/// <summary>
/// 双击修改事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
int index = this.dataGridView1.CurrentRow.Index;
this.txtName.Text = this.dataGridView1.Rows[index].Cells[1].Value.ToString();
}
/// <summary>
/// 修改事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click_1(object sender, EventArgs e)
{
string name = this.txtName.Text.Trim().ToString();
int id = Convert.ToInt32(this.dataGridView1.Rows[this.dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
Table<ClassDemo> table = dc.GetTable<ClassDemo>();
IQueryable<ClassDemo> tab = table.Where(i => i.Id == id);
foreach (var item in tab.AsEnumerable())
{
item.Name = name;
}
dc.SubmitChanges();
Bind();
}
/// <summary>
/// 删除
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click_1(object sender, EventArgs e)
{
int id = Convert.ToInt32(this.dataGridView1.Rows[this.dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
Table<ClassDemo> table = dc.GetTable<ClassDemo>();
var query = from value in table
where value.Id == id
select value;
table.DeleteAllOnSubmit(query);
dc.SubmitChanges();
Bind();
}