linq链接数据库SQL封装类
首先,需要定义一个LINQ to SQL的上下文类,这个类是从DataContext继承而来,并且包含了映射到数据库表的实体类。
[Database(Name="MyDatabase")]
public class MyDataContext : DataContext
{
public Table<User> Users;
public MyDataContext(string connectionString) : base(connectionString) { }
}
[Table(Name="Users")]
public class User
{
[Column(IsPrimaryKey=true)]
public int Id;
[Column(Name="Name")]
public string Name;
[Column(Name="Age")]
public int Age;
}
然后,可以创建一个封装了数据库连接的类,用于执行查询操作:
public class DataRepository
{
private string connectionString = "Data Source=服务器地址;Initial Catalog=数据库名;Persist Security Info=True;User ID=用户名;Password=密码";
public IEnumerable<User> GetAllUsers()
{
using (var db = new MyDataContext(connectionString))
{
return db.Users.ToList();
}
}
public User GetUserById(int id)
{
using (var db = new MyDataContext(connectionString))
{
return db.Users.FirstOrDefault(u => u.Id == id);
}
}
public void AddUser(User user)
{
using (var db = new MyDataContext(connectionString))
{
db.Users.InsertOnSubmit(user);
db.SubmitChanges();
}
}
// 其他数据库操作...
}
标签:封装,Name,数据库,connectionString,db,linq,SQL,public,Users
From: https://www.cnblogs.com/CloakBlowing/p/18086729