Db Attribute(Custom ORM ) Usage

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值