Db Attribute(Custom ORM ) Usage

2974 ワード

Db Attribute Usage 1. Attribute Defination
Db
  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
    public class DataBaseAttribute : System.Attribute
    {
        public string Name { get; private set; }

        public DataBaseAttribute(string name)
        {
            Name = name;
        }
    }

DataTable
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
    public class DataTableAttribute : System.Attribute
    {
        public string Name { get; private set; }

        public DataTableAttribute(string name)
        {
            Name = name;
        }
    }

Primary Key
 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false,Inherited = false)]
    public class PrimaryKeyAttribute : System.Attribute
    {
        public bool IsAutoIncreased { get; private set; }
        public string Name { get; private set; }
        public PrimaryKeyAttribute(string name,bool isAutoIncreased)
        {
            IsAutoIncreased = isAutoIncreased;
            Name = name;
        }

    }

2. Use Attribute to Entity
Db
    [DataBase("northwnd")]
    public class IoriRepository<T> : IRepository<T> where T : new()

DataTable And Primary Key
   [DataTable("Products")]
    public class ProductEntity
    {
        [PrimaryKey("ProductId",true)]
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public int SupplierId { get; set; }
        public int CategoryId { get; set; }
        public string QuantityPerUnit { get; set; }
        public decimal UnitPrice { get; set; }
        public Int16 UnitsInStock { get; set; }
        public Int16 UnitsOnOrder { get; set; }
        public Int16 ReorderLevel { get; set; }
        public bool Discontinued { get; set; }
    }

3. Get Attribute Implementation
 public static class AttributeHelper 
    {
        public  static TAttrType GetFirstAttr<TAttrType, TClassType>(bool isInherit) where TAttrType : System.Attribute
        {
            var attrs = (TAttrType[])(typeof(TClassType).GetCustomAttributes(typeof(TAttrType), isInherit));
            return attrs.FirstOrDefault();
        }
    }


////get db name
            var dbAttr = AttributeHelper.GetFirstAttr<DataBaseAttribute, IoriRepository<T>>(false);
            if (dbAttr == null)
                throw new Exception("failed to get Database name , check if you forgot to set Database Attribute for Repository<T>");

Similarly , Can use the same method to get DataTable Attribute And Primary Key Attribute