ORM framework for learning (III)

ORM framework learning data -UPDATE

Update part of the implementation code

public bool Update<T>(T t) where T : BaseModel
        {

            try
            {
                Type type = typeof(T);
                string conStr = "Server=127.0.0.1;Database=master; integrated security=SSPI";
                string UpdateStr = SqlBuilder<T>.GetSql(SqlBuilder<T>.SqlType.UpdateSql);
                var sqlpara = type.GetProperties().Select(p => new SqlParameter("@" + p.GetMappingName(), p.GetValue(t) ?? DBNull.Value)).ToArray();
                using (SqlConnection conn = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand(UpdateStr, conn);
                    cmd.Parameters.AddRange(sqlpara);
                    conn.Open();
                    int result = cmd.ExecuteNonQuery();
                    return result > 0;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

The code and before the Insert ADD codes and similar in Update this one, major new point is: do the data characteristics of the updated filter . Because in our daily needs, the need for the user to fill in data transmitted back to do some data validation, to check whether these data are consistent with the provisions, such as some empty verification, validation length limit.

Entry code as follows

static void Main(string[] args)
        {
            SqlHelper help = new SqlHelper();
            UserModel u1 = help.Query<UserModel>(1);
            Company com1 = help.Query<Company>(2);
            bool re1 = help.AddData(u1);
            bool re2 = help.AddData(com1);
            u1.Names = "";
            if (!u1.Validate())
            {
                Console.WriteLine("验证未通过!");
                return;
            }
            bool re3 = help.Update(u1);
        }

Verification method call as shown at FIG.

 

 

Validate is a generic method used to define the data checking, is an extension method. Code implementation is as follows:

public static class ValidateExtend
    {
        public static bool Validate<T>(this T t) 
        {
            Type type=typeof(T);
            foreach (var prop in type.GetProperties())
            {
                var val = prop.GetValue(t);
                if (prop.IsDefined(typeof(ThemeValidate), true))
                {
                    foreach (var item in prop.GetCustomAttributes<ThemeValidate>())
                    {
                        if (!item.Validate(val))
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
    }

As shown in the code, the Validate extension method is a generic method, because the presence of this parameter is an extension method, it may be called directly by the object. In order to facilitate future expansion inspection rules, we abstracted a base class ThemeValidate , the future needs to be done to verify the characteristics of the class needs to inherit from ThemeValidate, ThemeValidate defined as follows:

public abstract class ThemeValidate:Attribute
    {
        public abstract bool Validate(object obj);
    }

ThemeValidate only defines an abstract method, then the method corresponding to the validation rules subclass. Let's look at the definition of a subclass of two ThemeValidate

ThemeRequireAttribute verification data can not be empty categories:

public class ThemeRequireAttribute : ThemeValidate
    {

        public override bool Validate(object obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))
            {
                return false;
            }
            return true;
        }
    }

Subclasses authentication data length: ThemeAttributeStrLen

 public class ThemeAttributeStrLen : ThemeValidate
    {
        private int _Min = 0;
        private int _Max= 0;
        public ThemeAttributeStrLen(int min, int max)
        {
            this._Min = min;
            this._Max = max;
        }
        public override bool Validate(object obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()) || obj.ToString().Length > _Max || obj.ToString().Length < _Min)
            {
                return false;
            }
            return true;
        }
    }

Currently I define two or more sub-class verification, the future need to expand on their own to add, as long as the restrictions inherited from ThemeValidate on it.

Our validation features have been defined, which is above the two subclasses (ThemeAttributeStrLen and ThemeRequireAttribute), the next step is to mark these two characteristic properties of the entity class field to go.

In the current code, company and user entities on the characteristics mark made, user defined as follows:

public partial class UserModel:BaseModel
    {

        [StringLength(50), ThemeColumn("Name")]
        [ThemeRequireAttribute]
        [ThemeAttributeStrLen(10, 50)]
        public string Names { get; set; }

        [Required]
        [StringLength(100)]
        public string Account { get; set; }

        [Required]
        [StringLength(100)]
        public string Password { get; set; }

        [StringLength(200)]
        public string Email { get; set; }

        [StringLength(30)]
        public string Mobile { get; set; }

        public int? CompanyId { get; set; }

        [StringLength(500)]
        public string CompanyName { get; set; }

        public int State { get; set; }

        public int UserType { get; set; }

        public DateTime? LastLoginTime { get; set; }

        public DateTime CreateTime { get; set; }

        public int CreatorId { get; set; }

        public int? LastModifierId { get; set; }

        public DateTime? LastModifyTime { get; set; }
    }

As shown in the code, if there are a plurality of characteristic properties, it is defined as shown in FIG: This field contains the definition expressed Names four characteristic StringLength, ThemeColumn, ThemeRequireAttribute, ThemeAttributeStrLen.

 

Company characteristic shown labeled as follows

public partial class Company:BaseModel
    {
        

        [StringLength(500)]
        [ThemeRequireAttribute]
        [ThemeAttributeStrLen(10,50)]
        public string Name { get; set; }

        [ThemeRequireAttribute]
        public DateTime CreateTime { get; set; }

        [ThemeRequireAttribute]
        public int CreatorId { get; set; }

        [ThemeRequireAttribute]
        public int? LastModifierId { get; set; }

        [ThemeRequireAttribute]
        public DateTime? LastModifyTime { get; set; }
    }

 

Guess you like

Origin www.cnblogs.com/zxwDont/p/11490081.html