Handwritten ORM, core implementation

ORM object-relational mapping , the most famous is the EF net platform framework, and of course, dapper, EF easy to use, but he is too big, if it is a small project to write baa project is necessary, it is a relatively light dapper welterweight, and his maps that correspond to solid objects and parameters sql, ado.net closer, then we can write a orm What? Of course it can, in fact, no matter what the final bottom or sql statement, it is for net ADO.NET !
1, prior to this, you should understand the knowledge to write a reflection on!
Many times our entity and the field name is the name of the data table field is not the same, then we are through property field shoot at the entity fields to get!
For example entity definition:

[Table("[User]")]
public class User
{
    [Id("UserId", IsGenerated = true)]
    public int UserId { get; set; }

    [Column("Email")] 
    public string Email { get; set; }

    [Column("CreatedTime", false)]
    public DateTime CreatedTime { get; set; }
}

Define the characteristics of value, inheritance Attribute type, I came out here

 public class TableAttribute : Attribute
        {
            /// <summary>
            /// 表名
            /// </summary>
            public string Name { get; private set; }
    
            public TableAttribute(string name)
            {
                this.Name = name;
            }
        }
public class ColumnAttribute : Attribute
{
    /// <summary>
    /// 是否为数据库自动生成
    /// </summary>
    public bool IsGenerated { get; set; }
    /// <summary>
    /// 列名
    /// </summary>
    public string Name { get; set; }

    public ColumnAttribute(string name)
    {
        this.Name = name;
        this.IsMapping = true;
    }
    public bool IsMapping { get; set; }
    public ColumnAttribute(string name, bool IsMapping)
    {
        this.Name = name;
        this.IsMapping = IsMapping;
    }

Then write a short answer into the database method

 public class DBorm<T> where T : class
    {
        private static string connectionString = "";  //链接字符串

        public static int InsertEntity<T>(T Entity) 
    {
        var type = typeof(T);
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        var properties = type.GetProperties();   //通过反射的方式获取到了 特性

        string tableName = string.Empty;
        TableAttribute[] tableAttrs = (TableAttribute[])typeof(User).GetCustomAttributes(typeof(TableAttribute), true);
        if (tableAttrs.Length > 0)
        {
            tableName = tableAttrs[0].TableName;
        }
        else
        {
            tableName = type.Name;  //特性中的名字,
        }

        /*将所有的列放到集合里*/
        List<ColumnAttribute> columns = new List<ColumnAttribute>();
        for (int i = 0; i < properties.Length; i++)
        {
            var pi = properties[i];
            var attrs = (ColumnAttribute[])pi.GetCustomAttributes(typeof(ColumnAttribute), true);
            if (attrs.Length > 0)
            {
                columns.Add(attrs[0]);
            }
        }
       
       //构造sql语句
        StringBuilder sql = new StringBuilder();
        sql.Append("INSERT INTO [").Append(tableName).Append("](");
        int paramIndex = 0;

        for (int i = 0; i < properties.Length; i++)
        {
            var pi = properties[i];
            var attrs = (ColumnAttribute[])pi.GetCustomAttributes(typeof(ColumnAttribute), true);
            if (attrs.Length > 0 && attrs[0].IsGenerated == false && attrs[0].IsMapping == true)
            {
                if (paramIndex > 0)
                    sql.Append(",");

                sql.Append(attrs[0].Name);
                paramIndex++;
            }
        }

        sql.Append(") VALUES (");
        paramIndex = 0;
        for (int i = 0; i < properties.Length; i++)
        {
            var pi = properties[i];
            var attrs = (ColumnAttribute[])pi.GetCustomAttributes(typeof(ColumnAttribute), true);
            if (attrs.Length > 0 && attrs[0].IsGenerated == false && attrs[0].IsMapping == true)
            {
                if (paramIndex > 0)
                    sql.Append(",");

                sql.Append("@p").Append(paramIndex);
                parameters.Add("@p" + paramIndex, pi.GetValue(Entity, null));
                paramIndex++;
            }
        }

        sql.Append(")");

        SqlConnection conn = new SqlConnection(connectionString);
        var cmd = conn.CreateCommand();
        cmd.CommandText = sql.ToString();
        foreach (var item in parameters)
        {
            var pa = cmd.CreateParameter();
            pa.ParameterName = item.Key;
            pa.Value = item.Value ?? DBNull.Value;
            cmd.Parameters.Add(pa);
        }

        conn.Open();
        return cmd.ExecuteNonQuery();

    }
}

Simple look, is very simple, very quickly is to achieve a reflection achieved through the operation of ORM, usually busy working, only to quickly write down some of the core things, of course, himself wrote a more complete ORM framework , followed by time to write, welcomed the guidance!

Guess you like

Origin blog.csdn.net/weixin_42780928/article/details/93326681