赞
踩
今天先记录一下如何通过自定义attribute类实现对类名、属性名和关系数据库中的表名、字段名等信息映射。关于attribute类网上资料很多,这里不详细介绍了,下面具体代码中用到的地方会有具体说明。
首先需要自定义三个attribute类,分别是TableAttribute、ColumnAttribute和PrimaryKeyAttribute,这三个类将分别描述表名、字段名和主键名。下面是具体的实现。
1.TableAttribute
- using System;
-
- namespace ORM
- {
- [AttributeUsage(AttributeTargets.Class)]
- public class TableAttribute : Attribute
- {
- public TableAttribute(string tableName)
- {
- this.Value = tableName;
- }
-
- public string Value { get; protected set; }
- }
- }
2.ColumnAttribute
- using System;
-
- namespace ORM
- {
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
- public class ColumnAttribute : Attribute
- {
- public ColumnAttribute(string columnName)
- {
- this.Value = columnName;
- }
-
- public string Value { get; protected set; }
- }
- }
3.PrimaryKeyAttribute
- using System;
-
- namespace ORM
- {
- [AttributeUsage(AttributeTargets.Class)]
- public class PrimaryKeyAttribute : Attribute
- {
- public PrimaryKeyAttribute(string primaryKey)
- {
- this.Value = primaryKey;
- }
-
- public string Value { get; protected set; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。