1.添加linq to sql到项目中
2.确认后项目多了如下文件
3.链接到服务器
连接上服务器 选择好数据库 确认
4.拖动数据库上的表到dbml的设计器上,自动生成表对应的orm类,保存生成
开始编写代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace linqToSql
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext db = new DataClasses1DataContext();
// 注意 增删改 的表必须要有主键
// 增 数据库表添加一个数据
db.customer.InsertOnSubmit(new customer() { AcNo = "6666", Name = "test", Sales = "777888", MasterPassword = "123", InputUser = "test", PhoneTradePassword = "1234", IdentityNo = "13633333333", Email = "6666@qq.com", Phone = "26226626262", InputDate = System.DateTime.Now });
db.SubmitChanges();
// 改
db.customer.First(M => M.AcNo == "6666").Name = "UpdateTest";
db.SubmitChanges();
// 删
db.customer.DeleteOnSubmit(db.customer.First(M => M.AcNo == "6666"));
db.SubmitChanges();
// 查
IQueryable<customer> customerList = db.customer.Where(M => M.AcNo == "6666");
foreach (customer item in customerList)
{
Console.WriteLine(item.AcNo);
}
// 调用自定义直接查询语句
IEnumerable list1 = db.ExecuteQuery(typeof(customer), "select * from customer where AcNo={0}", new object[] { "6666" });
foreach (customer item in list1)
{
Console.WriteLine(item.Name);
}
IEnumerable<customer> list2 = db.ExecuteQuery<customer>("select * from customer where AcNo={0}", new object[] { "6666" });
foreach (customer item in list2)
{
Console.WriteLine(item.Name);
}
// 执行命令
db.ExecuteCommand(@"insert into [customer]([AcNo],[Name],[Email],Gender,[Phone],[IdentityNo],[MasterPassword],[PhoneTradePassword],[InputDate],[InputUser],[Sales])
values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10})", new object[] { "77777", "test7777", "7777@qq.com",0 ,"13333333333", "77777777777", "77777password", "7777777password", System.DateTime.Now, "7777", "777888" });
Console.Read();
}
}
}