【ASP.NET程序员福利】打造一款人见人爱的ORM(二)

上一篇我已经给大家介绍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.数据库配置

 1   <AppSettings>
 2     <DatabaseName>antormsqlite</DatabaseName>
 3     <DatabaseType>mssql</DatabaseType>
 4     <!--oledb:Access数据库;mssql:SQL数据库;oracle:oracle数据库;SQLite:SQLite小型数据库-->
 5     <IsConStringEncrypt>true</IsConStringEncrypt>
 6     <DatabaseKey>A949564832391559D9994800BB8F283D8FB44CCE5FAA0246574C4A247C39F2B2DA3425F0B23582C13BC5FDAD2AED1A33</DatabaseKey>
 7     <ReadData>user id=sa;password=a1b2c3d4@admin;DataBase=OOExceptionHandle;server=1.41.107.147;</ReadData>
 8     <!--1.41.107.147-->
 9     <WriteData>user id=sa;password=a1b2c3d4@admin;DataBase=OOExceptionHandle;server=1.41.107.147;</WriteData>
10   </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实现查询

  查询单一实体方法一

 1             using (AntORM orm = new AntORM())
 2             {
 3 
 4                 orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");//SQLite
 5                 orm.ModuleName = "antormsqlite";//SQLite
 6                 var q = orm.Queryable<User>();
 7                 RequestModel rest = new RequestModel();
 8                 rest.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询用户信息单个实体方法" };
 9                 var mod = q.Where(a => a.Id == 12).FirstOrDefault();
10                 if (mod.IsSuccess)
11                 {
12                     User user = mod.ResultModel;
13                 }
14              }

  查询单一实体方法二

 1            using (AntORM orm = new AntORM())
 2             {
 4                 var request = new RequestModel();
 5                 request.db = DataAccessFactory.CreateDataConnection("antormsqlite");
 6                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
 7                 User query = new User();
 8                 query.Id = 5;
 9                 var reslut = orm.GetEntity(query, request);
10                 if (reslut.IsSuccess)
11                 {
12                     User user = reslut.ResultModel;
13                 }
14             }

 如果只能通主键去查询,还可以这样写

 1            using (AntORM orm = new AntORM())
 2             {
 3                var  request = new RequestModel();
 4                 request.db = DataAccessFactory.CreateDataConnection("antormsqlite");
 5                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
 6                 request.Oid = "5";
 7                 var res = orm.GetEntity<User>(request);
 8                 if (res.IsSuccess)
 9                 {
10                     User user = res.ResultModel;
11                 }
12             }

 查询带分页方法一

 1            using (AntORM orm = new AntORM())
 2             {
 3                 RequestModel request = new RequestModel();
 4                 request.db = DataAccessFactory.GetWriteDataDefault;
 5                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
 6                 var q = orm.Queryable<User>();
 7                 //分页
 8                 var relust = q.Where(a => a.Id > 0).OrderBy(a => a.Age).ThenByDesc(a => a.Id).Top(10).Skip(1).ToList(request);
 9                 if(relust.IsSuccess)
10                 {
11                     var userlist = relust.ResultModel;
12                 }
13             }

查询带分页方法二

 1             using (AntORM orm = new AntORM())
 2             {
 3                 RequestModel request = new RequestModel();
 4                 request.ModuleName = "antormsqlite";
 5                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
 6                 User query = new User();
 7                 query.CityId = 2;
 8                 var reslut = orm.GetPageList(query, request);
 9                 if (reslut.IsSuccess)
10                 {
11                     var userlist = reslut.ResultModel;
12                 }
13             }

多表查询的方法

 1             using (AntORM orm = new AntORM())
 2             {
 3                 orm.db = DataAccessFactory.GetWriteDataDefault;
 4                 var users = orm.Queryable<User>();
 5                 var cities = orm.Queryable<City>();
 6                 var provinces = orm.Queryable<Province>();
 7                 //建立连接
 8                 var user_city = users.InnerJoin(cities, (user, city) => user.CityId == city.Id && user.Id > 0);
 9                 var user_city_province = user_city.InnerJoin(provinces, (user, city, province) => (city.ProvinceId == province.Id));
10 
11                 RequestModel request = new RequestModel();
12                 request.db = DataAccessFactory.GetWriteDataDefault;
13                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查出一个用户及其隶属的城市和省份的所有信息三张表数据都返回出来" };
14                 var reslut = user_city_province.Select((user, city, province) => new { Users = user, Citys = city, Provinces = province })
15                     .Where(a => a.Users.Id == 3 && a.Citys.Name == "30").OrderByDesc(p => p.Users.Id).ToList(request);
16                 if(reslut.IsSuccess)
17                 {
18                     var userlist = reslut.ResultModel;
19                 }
20             }

 实现查询带In操作

 1             using (AntORM orm = new AntORM())
 2             {
 3                 orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");
 4                 RequestModel request = new RequestModel();
 5                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询用户名称带这几个人实现In操作的方法" };
 6                 string[] Names = { "lu", "jjg1", "jjg3" };
 7                 var reslut = orm.Queryable<User>().Where(p => Names.Contains(p.Name)).Select(p => new { p.Name, p.CityId }).ToList();
 8                 if (reslut.IsSuccess)
 9                 {
10                     var mod = reslut.ResultModel;
11                 }
12             }

 通过orm拼接条件来查询

 1             using (AntORM orm = new AntORM())
 2             {
 3                var request = new RequestModel();
 4                 request.db = DataAccessFactory.GetWriteDataDefault;
 5                 request.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "通过拼接条件来查询的方法" };
 6                 User m = new User();
 7                 m.Age = 20;
 8                 IList<IPredicate> predList = new List<IPredicate>();
 9                 var query1 = Predicates.QueryField<User>(p => p.CityId, Operator.Equal, "1");
10                 predList.Add(query1);
11                 var query2 = Predicates.QueryField<User>(p => p.CityId, Operator.Equal, "1");
12                 predList.Add(query2);
13                 IPredicateGroup query = Predicates.SqlGroup(GroupOperator.And, predList.ToArray());
14                 request.Predicate =query;
15                 var reslut = orm.GetDr2EnList(m, request);
16                 if (reslut.IsSuccess)
17                 {
18                     var modlist = reslut.ResultModel;
19                 }
20             }

 通过自定义SQL查询操作

 1         /// <summary>
 2         /// 自定义SQL操作
 3         /// </summary>
 4         /// <param name="request"></param>
 5         /// <returns></returns>
 6         public static ResponseModel AntOrmItemSQL(RequestModel request)
 7         {
 8             ResponseModel reslut = new ResponseModel();
 9             using (AntORM orm = new AntORM())
10             {
11                 int id = 1;
12                 orm.ModuleName = "antormsqlite";
13                 var list = orm.SqlQuery<User>(string.Format("select top {0} * from Users where Id>@Id", 1), new { Id = id }).Select(p => new { p.Name }).ToList();
14                 if (list.IfNotNull() || list.Count > 0)
15                 {
16                     reslut.ResultModel = list;
17                     reslut.IsSuccess = true;
18                 }
19                 return reslut;
20             }
21         }

实现分组查询

 1         /// <summary>
 2         /// 分组查询
 3         /// </summary>
 4         /// <param name="request"></param>
 5         /// <returns></returns>
 6         public static ResponseModel GroupQuery(RequestModel request)
 7         {
 8             using (AntORM orm = new AntORM())
 9             {
10                 var q = orm.Queryable<User>();
11 
12                 IGroupingQuery<User> g = q.Where(a => a.Id > 0).GroupBy(a => a.Age);
13 
14                 g = g.Having(a => a.Age > 1 && AggregateFunctions.Count() > 0);
15 
16                 var res = g.Select(a => new
17                 {
18                     a.Age,
19                     Count = AggregateFunctions.Count(),
20                     Sum = AggregateFunctions.Sum(a.Age),
21                     Max = AggregateFunctions.Max(a.Age),
22                     Min = AggregateFunctions.Min(a.Age),
23                     Avg = AggregateFunctions.Average(a.Age)
24                 }).ToList(request);
25                 return res;
26             }
27         }

2.AntORM实现新增修改删除操作

 1         /// <summary>
 2         /// 实现保存操作
 3         /// </summary>
 4         public static ResponseModel UserSave(RequestModel request)
 5         {
 6             User mod = new User();
 7             using (AntORM orm = new AntORM())
 8             {
 9 
10                 orm.db = DataAccessFactory.CreateDataConnection("antormsqlite");//SQLite
11 
12                 var reslut = orm.Queryable<User>().Where(p => p.Id == 5).FirstOrDefault();
13                 if (reslut.IsSuccess)
14                 {
15                     mod = reslut.ResultModel;//实现的修改
16                 }
17                 else
18                 {
19                     mod = new User() { Name = "jjg4", Age = 30, Gender = Gender.Man, CityId = 2, OpTime = DateTime.Now };//实现的新增
20 
21                 }
22                 //第一种保存
23                 reslut = orm.SaveHaveNull(mod, request);//保存数据(新增和更新)数据库没有Null值
24                 //return reslut;
25 
26                 //第二种保存reslut
27                 reslut = orm.Save(mod, request);//根据实体来进行插入数据库的表中带Null值
28                 return reslut;
29 
30             }
31         }

 

        /// <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实现事务操作

 1     /// <summary>
 2         /// 实现事务要保证数据库连接db是同一个,不能重新创建新的数据库连接
 3         /// </summary>
 4         public static ResponseModel CommitTransaction(RequestModel request)
 5         {
 6             User mod = new User();
 7             using (AntORM orm = new AntORM())
 8             {
 9 
10                 using (orm.db = DataAccessFactory.CreateDataConnection("antormsqlite"))//SQLite
11                 {
12                     orm.db.BeginTransaction();
13                     try
14                     {
15                         User query = new User();
16                         query.Id = 5;
17                         var reslut = orm.GetEntity(query, request);
18                         if (reslut.IsSuccess)
19                         {
20                             mod = reslut.ResultModel;//实现的修改
21                             reslut = orm.Save(mod, request);//保存数据(新增和更新)数据库没有Null值
22                             reslut = orm.DeleteByModel(query, request);
23 
24                         }
25                         else
26                         {
27                             reslut.IsSuccess = false;
28                             reslut.Message = "查询数据失败";
29                         }
30                         orm.db.Commit();
31 
32                         return reslut;
33                     }
34                     catch (Exception ex)
35                     {
36                         orm.db.RollBack();
37                         ResponseModel reslut = new ResponseModel();
38                         reslut.IsSuccess = false;
39                         reslut.Message = "事务中执行报错" + ex.ToString();
40                         return reslut;
41                     }
42 
43                 }
44             }
45         }

 

 


转载于:https://www.cnblogs.com/jjg0519/p/6085552.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值