运用SqlSugar框架+Axios写的增删查案例
使用SqlSugar框架需要引用NuGet程序包否则会出现报错。
前台页面创建代码:
@{
ViewBag.Title = "Index";
}
Index
姓名: | |
---|---|
手机号: | |
密码: | |
状态: | |
编号 | 用户名 | 手机号 | 密码 | 状态 | 操作 |
@item.UserID | @item.UserName | @item.PhoneNumber | @item.UserPassword | @item.UserState | 删除 修改 |
创建Config.CS链接数据库
public class Config
{
///
/// 数据库连接字符串(私有字段)
///
private static readonly string _connectionString = System.Configuration.
ConfigurationManager.ConnectionStrings["SqlServerConn"].ToString();
///
/// 数据库连接字符串(公有属性)
///
public static string ConnectionString
{
get { return _connectionString; }
}
}
创建DBSuglar.CS
public class DBSuglar
{
public static SqlSugarClient GetSqlSugarClient()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,//必填, 数据库连接字符串
DbType = DbType.SqlServer, //必填, 数据库类型
IsAutoCloseConnection = true, //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
InitKeyType = InitKeyType.SystemTable //默认SystemTable, 字段信息读取, 如:该属性是不是主键,是不是标识列等等信息
});
return db;
}
}
创建实体类User.cs
public class User
{
public List
{
return Users.GetAll().ToList();
}
public bool Delete(int id)
{
return Users.Delete(id);
}
public bool Insert(UserInfo us)
{
return Users.Insert(us);
}
}
创建Home控制器
public class HomeController : Controller
{
public static SqlSugarClient db = DBSuglar.GetSqlSugarClient();
User us = new User();
///
/// 查询
///
///
public ActionResult Index()
{
ViewBag.data = db.SqlQueryable
return View();
}
///
/// 删除
///
/// 删除的主键
///
public ActionResult Delete(int id)
{
db.Deleteable
return RedirectToAction("Index");
}
///
/// 添加
///
public ActionResult Insert(UserInfo users)
{
var i= db.Insertable(users).ExecuteReturnBigIdentity();
return Json(i,JsonRequestBehavior.AllowGet);
}
}
整体页面效果