1. 新建一个工程
2. 创建数据库,添加表,然后在VS中的Server Explorer中连接到数据库。
3. 在工程中添加LINQ to SQL Classes,随便命名。然后将刚才的数据表拖进来。保存,OK。
以下是示例代码:
namespace LinqToSQLWinform { public partial class Form1 : Form { DBDataContext db = new DBDataContext(); public Form1() { InitializeComponent(); } /// <summary> /// Add user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAdd_Click(object sender, EventArgs e) { var uu = db.Users.SingleOrDefault<User>(u => u.ID == txtID.Text); if (uu != null) { User user = new User { ID = txtID.Text, Name = txtName.Text, Age = txtAge.Text, Address = txtAddr.Text }; db.Users.InsertOnSubmit(user); db.SubmitChanges(); MessageBox.Show("Add user successed"); txtID.Text = txtName.Text = txtAge.Text = txtAddr.Text = ""; } else MessageBox.Show("This user is exist"); } /// <summary> /// Query user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnQuery_Click(object sender, EventArgs e) { var u = from uu in db.Users where uu.ID == txtID.Text select uu; if (u.Count() > 0) { User user = u.FirstOrDefault(); txtName.Text = user.Name; txtAge.Text = user.Age; txtAddr.Text = user.Address; } } /// <summary> /// Update user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUpdate_Click(object sender, EventArgs e) { var user = db.Users.SingleOrDefault<User>(u => u.ID == txtID.Text); if (user != null) { user.Name = txtName.Text; user.Age = txtAge.Text; user.Address = txtAddr.Text; db.SubmitChanges(); MessageBox.Show("Update user successed"); } else MessageBox.Show("This user is exist"); } /// <summary> /// Delete user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnDelete_Click(object sender, EventArgs e) { var user = db.Users.SingleOrDefault<User>(u => u.ID == txtID.Text); if (user != null) { db.Users.DeleteOnSubmit(user); db.SubmitChanges(); MessageBox.Show("Delete user successed"); } else MessageBox.Show("This user is exist"); } } }