Handwritten ORM Beginners (a)

Object-Relational Mapping (English: (Object Relational Mapping, referred to as the ORM, or O / RM, or O / R mapping), is a program technique for conversion between the object-oriented programming language systems different types of data [ 1] in effect that it actually creates a usable programming language - a "virtual object database."

Is from the mathematical theory developed from two significant differences from the theoretical basic principles of object-oriented software engineering (e.g., coupling, polymerization, package) developed on the basis of the relational database. To solve this mismatch phenomenon, object-relational mapping technology came into being.

Object-Relational Mapping (Object-Relational Mapping) provides a conceptual model-based data it can be easily understood. ORM methodology is based on three core principles: Simple: The most basic form of modeling data. Communicability: database structure is that anyone can understand the language of the document. Accuracy: create the proper structure is based on a standardized data model. Typically, the modeler by collecting from people who are familiar with the application, but the data modeler unskilled Information Development information model. Modeling must be able to use non-technical business experts can understand the terminology to communicate with the data structure on the conceptual level. Modeling must also be able to analyze information in a simple unit, the sample data is processed. ORM is specifically designed to improve such a link.

Simply put: ORM equivalent to relay data. Specific to the product, such as ADO.NET Entity Framework. DLINQ entity attribute classes [the Table] Even if the data is a relay.

BaseModel Sample code:

    public  class BaseModel 
    { 
        ///  <Summary> 
        /// describe all non-automatic primary key table the GUID
         ///  </ Summary> 
        public  String Id { SET ; GET ;} 
    }

User Code Example:

 1     public class User : BaseModel
 2     {
 3         public string Account { get; set; }
 4 
 5         public string Password { get; set; }
 6 
 7         public string Name { get; set; }
 8 
 9         public int Sex { get; set; }
10 
11         public int Status { get; set; }
12 
13         public string BizCode { get; set; }
14 
15         public DateTime CreateTime { get; set; }
16 
17         public string CrateId { get; set; }
18 
19         public string TypeName { get; set; }
20 
21         public string TypeId { get; set; }
22 
23     }

IBaseDAL Sample code:

1  public interface IBaseDAL
2     {
3         T Find<T>(string id) where T : BaseModel;
4         List<T> FindAll<T>() where T : BaseModel;
5         bool Add<T>(T t) where T : BaseModel;
6         bool Update<T>(T t) where T : BaseModel;
7         bool Delete<T>(T t) where T : BaseModel;
8     }

BaseDAL Sample Code

  . 1      ///  <Summary> 
  2      /// generic method BaseModel added constraint, all entities must have a primary key Id is a non-increment, a random value Id the GUID,
   . 3      ///  </ Summary> 
  . 4      public  class BaseDAL: IBaseDAL
   . 5      {
   . 6          ///  <Summary> 
  . 7          /// connection string
   . 8          ///  </ Summary> 
  . 9          Private  static  string the ConnectionString ConfigurationManager.ConnectionStrings = [ " OpenAuthDB " ] .ConnectionString;
 10  
. 11          public  BOOL the Add <T> (T T) WHERE T : BaseModel
 12         {
 13             Type type = t.GetType();
 14             string columnStr = string.Join(",", type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => $"[{p.Name}]"));
 15             string valueStr = string.Join(",", type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => $"@{p.Name}"));
 16             var parameterList = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => new SqlParameter($"@{p.Name}", p.GetValue(t) ?? DBNull.Value));
 17             string sqlStr = $"Insert Into [{type.Name}] ({columnStr}) values ({valueStr})";
 18             using (SqlConnection conn = new SqlConnection(ConnectionString))
 19             {
 20                 SqlCommand command = new SqlCommand(sqlStr, conn);
 21                 command.Parameters.AddRange(parameterList.ToArray());
 22                 conn.Open ();
 23 is                  // If Id is incremented, and in a later increase sql Select @@ Identity; command.ExecuteScalar, after the new Id out. 
24                  return command.ExecuteNonQuery ()> 0 ;
 25              }
 26 is          }
 27  
28          public  BOOL the Delete <T> (T T) WHERE T: BaseModel
 29          {
 30              // get the type of T 
31 is              the type type = typeof (T);
 32              var Parameter = new new the SqlParameter ( " Id " , type.GetProperty ( 'Id").GetValue(t) ?? DBNull.Value);
 33             string strSql = $"DELETE FROM [{type.Name}] WHERE Id = @Id";
 34             using (SqlConnection conn = new SqlConnection(ConnectionString))
 35             {
 36                 SqlCommand command = new SqlCommand(strSql, conn);
 37                 command.Parameters.Add(parameter);
 38                 conn.Open();
 39                 var iRes = command.ExecuteNonQuery();
 40                 return iRes > 0 ? true : false;
 41             }
 42         }
 43 
 44         public List<T> FindAll<T>() where T : BaseModel
 45         {
 46             Type type = typeof(T);
 47             string sqlStr = $"SELECT {string.Join(",", type.GetProperties().Select(p => $"[{p.Name}]"))} FROM [{type.Name}]";
 48             List<T> list = new List<T>();
 49             using (SqlConnection conn = new SqlConnection(ConnectionString))
 50             {
 51                 SqlCommand command = new SqlCommand(sqlStr, conn);
 52                 conn.Open();
 53                 var reader = command.ExecuteReader();
 54                 while (reader.Read())
 55                 {
 56                     list.Add(this.Trans<T>(type, reader));
 57                 }
 58             }
 59             return list;
 60         }
 61 
 62         public T Find<T>(string id) where T : BaseModel
 63         {
 64             Type type = typeof(T);
 65             string sql = $"SELECT {string.Join(",", type.GetProperties().Select(p => $"[{p.Name}]"))} FROM [{type.Name}] WHERE ID = '{id}' ";
 66             object oObject = Activator.CreateInstance(type);
 67             using (SqlConnection conn = new SqlConnection(ConnectionString))
 68             {
 69                 SqlCommand command = new SqlCommand(sql, conn);
 70                 conn.Open();
 71                 var reader = command.ExecuteReader();
 72                 if (reader.Read())
 73                     return this.Trans<T>(type, reader);
 74                 else
 75                     return default(T);
 76             }
 77         }
 78 
 79         public bool Update<T>(T t) where T : BaseModel
 80         {
 81             Type type = typeof(T);
 82             StringBuilder sb = new StringBuilder();
 83             sb.Append($"UPDATE [{type.Name}] SET ");
 84             var propArray = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
 85             var propArrayLen = propArray.Count();
 86             for (int i = 0; i < propArrayLen; i++)
 87             {
 88                 var propertiesName = propArray[i].Name;
 89                 if (i != propArrayLen - 1)
 90                     sb.Append($"{propertiesName} = @{propertiesName}, ");
 91                 else
 92                     sb.Append($" {propertiesName} = @{propertiesName} ");
 93             }
 94             #region 使用foreach的写法
 95             //foreach (var properties in propArray)
 96             //{
 97             //    var propertiesName = properties.Name;
 98             //    if (i != propArrayLen)
 99             //        sb.Append($"{propertiesName} = @{propertiesName}, ");
100             //    else
101             //        sb.Append($" {propertiesName} = @{propertiesName} ");
102             //    i++;
103             //}
104             #endregion
105             sb.Append($" Where Id = @Id;");
106             var parameterList = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => new SqlParameter($"@{p.Name}", p.GetValue(t) ?? DBNull.Value));
107             using (SqlConnection conn = new SqlConnection(ConnectionString))
108             {
109                 SqlCommand command = new SqlCommand(sb.ToString(), conn);
110                 command.Parameters.AddRange(parameterList.ToArray());
111                 conn.Open();
112                 return command.ExecuteNonQuery() > 0;
113             }
114         }
115 
116         #region Private Method
117         private T Trans<T>(Type type, SqlDataReader reader)
118         {
119             object oObject = Activator.CreateInstance(type);
120             foreach (var properties in type.GetProperties())
121             {
122                 properties.SetValue(oObject, reader[properties.Name] ?? DBNull.Value);
123             }
124             return (T)oObject;
125         }
126         #endregion
127     }

 

Guess you like

Origin www.cnblogs.com/netlws/p/11028722.html