上一篇我已经给大家介绍AntORM的框架【ASP.NET程序员福利】打造一款人见人爱的ORM(一),今天就来着重介绍一下如何使用这套框架
1>AntORM 所有成员
如果你只想操作一种数据库,可以针对不同数据库选择独立的dll
Asp.net 4.+ |
说明 |
依赖 |
Ant.ORM.dll |
负责实体和数据库之间解析 |
Ant.Data.dll |
Ant.Data.dll |
数据库访问层 |
MySql.Data.dll System.Data.SQLite.dll Oracle.ManagedDataAccess.dll SQLite.Interop.dll |
Ant.Common.dll |
公共组件 |
无 |
2>数据库连接
1.普通模式
这种模式简单粗爆,适合一个产品支持多种数据库,但是中间没有两种数据库同时操作。
在用数据库连接的时候这两个名称要一样才能读取数据库配置信息
2.灵活模式
适合多种数据库混用项目
从上面图中可以看出,可以支持读写库进行配置分离。
3.数据库配置
<AppSettings>
<DatabaseName>antormsqlite</DatabaseName>
<DatabaseType>mssql</DatabaseType>
<!--oledb:Access数据库;mssql:SQL数据库;oracle:oracle数据库;SQLite:SQLite小型数据库-->
<IsConStringEncrypt>true</IsConStringEncrypt>
<DatabaseKey>A949564832391559D9994800BB8F283D8FB44CCE5FAA0246574C4A247C39F2B2DA3425F0B23582C13BC5FDAD2AED1A33</DatabaseKey>
<ReadData>user id=sa;password=a1b2c3d4@admin;DataBase=OOExceptionHandle;server=1.41.107.147;</ReadData>
<!--1.41.107.147-->
<WriteData>user id=sa;password=a1b2c3d4@admin;DataBase=OOExceptionHandle;server=1.41.107.147;</WriteData>
</AppSettings>
3>增删查改多表操作以及事务
项目中用到的实体:
1 public enum Gender
2 {
3 Man = 1,
4 Woman
5 }
6
7 [Table("Users")]
8 public class User : BaseEntityObj
9 {
10 public User()
11 {
12
13 }
14
15 [Column("id", IsPrimaryKey = true), AutoIncrement]
16 public int? Id { get; set; }
17
18 private string name;
19 public string Name
20 {
21 get { return name; }
22 set { name = value; }
23 }
24 public Gender? Gender { get; set; }
25 private int? age;
26 public int? Age
27 {
28 get { return age; }
29 set { age = value; }
30 }
31 public int? CityId { get; set; }
32 public DateTime? OpTime { get; set; }
33
34 }
1.AntORM实现查询
查询单一实体方法一
using (AntORM orm = new AntORM())
{ orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");//SQLite
orm.ModuleName = "antormsqlite";//SQLite
var q = orm.Queryable<User>();
RequestModel rest = new RequestModel();
rest.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询用户信息单个实体方法" };
var mod = q.Where(a => a.Id == ).FirstOrDefault();
if (mod.IsSuccess)
{
User user = mod.ResultModel;
}
}
查询单一实体方法二
using (AntORM orm = new AntORM())
{
var request = new RequestModel();
request.db = DataAccessFactory.CreateDataConnection("antormsqlite");
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
User query = new User();
query.Id = ;
var reslut = orm.GetEntity(query, request);
if (reslut.IsSuccess)
{
User user = reslut.ResultModel;
}
}
如果只能通主键去查询,还可以这样写
using (AntORM orm = new AntORM())
{
var request = new RequestModel();
request.db = DataAccessFactory.CreateDataConnection("antormsqlite");
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
request.Oid = "";
var res = orm.GetEntity<User>(request);
if (res.IsSuccess)
{
User user = res.ResultModel;
}
}
查询带分页方法一
using (AntORM orm = new AntORM())
{
RequestModel request = new RequestModel();
request.db = DataAccessFactory.GetWriteDataDefault;
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
var q = orm.Queryable<User>();
//分页
var relust = q.Where(a => a.Id > ).OrderBy(a => a.Age).ThenByDesc(a => a.Id).Top().Skip().ToList(request);
if(relust.IsSuccess)
{
var userlist = relust.ResultModel;
}
}
查询带分页方法二
using (AntORM orm = new AntORM())
{
RequestModel request = new RequestModel();
request.ModuleName = "antormsqlite";
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
User query = new User();
query.CityId = ;
var reslut = orm.GetPageList(query, request);
if (reslut.IsSuccess)
{
var userlist = reslut.ResultModel;
}
}
多表查询的方法
using (AntORM orm = new AntORM())
{
orm.db = DataAccessFactory.GetWriteDataDefault;
var users = orm.Queryable<User>();
var cities = orm.Queryable<City>();
var provinces = orm.Queryable<Province>();
//建立连接
var user_city = users.InnerJoin(cities, (user, city) => user.CityId == city.Id && user.Id > );
var user_city_province = user_city.InnerJoin(provinces, (user, city, province) => (city.ProvinceId == province.Id)); RequestModel request = new RequestModel();
request.db = DataAccessFactory.GetWriteDataDefault;
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查出一个用户及其隶属的城市和省份的所有信息三张表数据都返回出来" };
var reslut = user_city_province.Select((user, city, province) => new { Users = user, Citys = city, Provinces = province })
.Where(a => a.Users.Id == && a.Citys.Name == "").OrderByDesc(p => p.Users.Id).ToList(request);
if(reslut.IsSuccess)
{
var userlist = reslut.ResultModel;
}
}
实现查询带In操作
using (AntORM orm = new AntORM())
{
orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");
RequestModel request = new RequestModel();
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询用户名称带这几个人实现In操作的方法" };
string[] Names = { "lu", "jjg1", "jjg3" };
var reslut = orm.Queryable<User>().Where(p => Names.Contains(p.Name)).Select(p => new { p.Name, p.CityId }).ToList();
if (reslut.IsSuccess)
{
var mod = reslut.ResultModel;
}
}
通过orm拼接条件来查询
using (AntORM orm = new AntORM())
{
var request = new RequestModel();
request.db = DataAccessFactory.GetWriteDataDefault;
request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "通过拼接条件来查询的方法" };
User m = new User();
m.Age = ;
IList<IPredicate> predList = new List<IPredicate>();
var query1 = Predicates.QueryField<User>(p => p.CityId, Operator.Equal, "");
predList.Add(query1);
var query2 = Predicates.QueryField<User>(p => p.CityId, Operator.Equal, "");
predList.Add(query2);
IPredicateGroup query = Predicates.SqlGroup(GroupOperator.And, predList.ToArray());
request.Predicate =query;
var reslut = orm.GetDr2EnList(m, request);
if (reslut.IsSuccess)
{
var modlist = reslut.ResultModel;
}
}
通过自定义SQL查询操作
/// <summary>
/// 自定义SQL操作
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static ResponseModel AntOrmItemSQL(RequestModel request)
{
ResponseModel reslut = new ResponseModel();
using (AntORM orm = new AntORM())
{
int id = ;
orm.ModuleName = "antormsqlite";
var list = orm.SqlQuery<User>(string.Format("select top {0} * from Users where Id>@Id", ), new { Id = id }).Select(p => new { p.Name }).ToList();
if (list.IfNotNull() || list.Count > )
{
reslut.ResultModel = list;
reslut.IsSuccess = true;
}
return reslut;
}
}
实现分组查询
/// <summary>
/// 分组查询
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static ResponseModel GroupQuery(RequestModel request)
{
using (AntORM orm = new AntORM())
{
var q = orm.Queryable<User>(); IGroupingQuery<User> g = q.Where(a => a.Id > ).GroupBy(a => a.Age); g = g.Having(a => a.Age > && AggregateFunctions.Count() > ); var res = g.Select(a => new
{
a.Age,
Count = AggregateFunctions.Count(),
Sum = AggregateFunctions.Sum(a.Age),
Max = AggregateFunctions.Max(a.Age),
Min = AggregateFunctions.Min(a.Age),
Avg = AggregateFunctions.Average(a.Age)
}).ToList(request);
return res;
}
}
2.AntORM实现新增修改删除操作
/// <summary>
/// 实现保存操作
/// </summary>
public static ResponseModel UserSave(RequestModel request)
{
User mod = new User();
using (AntORM orm = new AntORM())
{ orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");//SQLite var reslut = orm.Queryable<User>().Where(p => p.Id == ).FirstOrDefault();
if (reslut.IsSuccess)
{
mod = reslut.ResultModel;//实现的修改
}
else
{
mod = new User() { Name = "jjg4", Age = , Gender = Gender.Man, CityId = , OpTime = DateTime.Now };//实现的新增 }
//第一种保存
reslut = orm.SaveHaveNull(mod, request);//保存数据(新增和更新)数据库没有Null值
//return reslut; //第二种保存reslut
reslut = orm.Save(mod, request);//根据实体来进行插入数据库的表中带Null值
return reslut; }
}
/// <summary>
/// 批量更新操作
/// </summary>
public static ResponseModel Update(RequestModel request)
{
ResponseModel reslut = new ResponseModel();
orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");//SQLite
using (AntORM orm = new AntORM())
{
#region 第一种更新方法
reslut = orm.UpdateByLambda<User>(a => new User() { Name = a.Name, Age = a.Age + 100, Gender = Gender.Man, OpTime = DateTime.Now }, a => a.Id == 1, request);
return reslut;
#endregion
#region 第二种更新方法
User user = new User();
user.Name = "ljjgu";
user.Age = 30;
user.Gender = Gender.Woman;
user.OpTime = DateTime.Now;
reslut = orm.UpdateById(user, request);//会更新所有映射的字段
if (reslut.IsSuccess)
{ //更新成功 }
#endregion
#region 第三种更新方法 /* * 支持只更新属性值已变的属性 */
user = new User();
user.Name = "ljjgu";
user.Age = 30;
user.Gender = Gender.Woman;
user.OpTime = DateTime.Now;
orm.TrackEntity(user);//这时只会更新被修改的字段 //在上下文中跟踪实体
user.Name = user.Name + "1";
reslut = orm.UpdateByLambda(user, a => a.Id == 2, request);
#endregion
#region 第四种更新方法批量更新 //批量更新 //给所有女性年轻 10 岁
reslut = orm.UpdateByLambda<User>(a => new User() { Age = a.Age - 10, OpTime = DateTime.Now }, a => a.Gender == Gender.Woman, request);
if (reslut.IsSuccess)
{ //更新成功 }
#endregion
}
}
}
}
/// <summary>
/// 删除操作
/// </summary>
public static ResponseModel Delete(RequestModel request)
{
using (AntORM orm = new AntORM())
{
#region 第一种删除方法 var reslut = orm.DeleteByLambda<User>(a => a.Id == 1, request); #endregion #region 第二种删除方法
//批量删除
//删除所有不男不女的用户
reslut= orm.DeleteByLambda<User>(a => a.Gender == null, request);
#endregion #region 第三种删除方法
User user = new User();
user.Id = 1;
reslut=orm.DeleteByModel(user, request); return reslut;
#endregion }
}
3.AntORM实现事务操作
/// <summary>
/// 实现事务要保证数据库连接db是同一个,不能重新创建新的数据库连接
/// </summary>
public static ResponseModel CommitTransaction(RequestModel request)
{
User mod = new User();
using (AntORM orm = new AntORM())
{ using (orm.db = DataAccessFactory.CreateDataConnection("antormsqlite"))//SQLite
{
orm.db.BeginTransaction();
try
{
User query = new User();
query.Id = ;
var reslut = orm.GetEntity(query, request);
if (reslut.IsSuccess)
{
mod = reslut.ResultModel;//实现的修改
reslut = orm.Save(mod, request);//保存数据(新增和更新)数据库没有Null值
reslut = orm.DeleteByModel(query, request); }
else
{
reslut.IsSuccess = false;
reslut.Message = "查询数据失败";
}
orm.db.Commit(); return reslut;
}
catch (Exception ex)
{
orm.db.RollBack();
ResponseModel reslut = new ResponseModel();
reslut.IsSuccess = false;
reslut.Message = "事务中执行报错" + ex.ToString();
return reslut;
} }
}
}