当前位置:   article > 正文

C#制作ORM映射学习笔记一 自定义Attribute类_"[tableattribute(dbname = \"gitwms\", name = \"acc

"[tableattribute(dbname = \"gitwms\", name = \"accinformation\", primarykeyname ="
之前在做unity项目时发现只能用odbc连接数据库,感觉非常的麻烦,因为之前做web开发的时候用惯了ORM映射,所以我想在unity中也用一下ORM(虽然我知道出于性能的考虑这样做事不好的,不过自己的小项目吗管他的,自己爽就行了)。不过现在世面上的ORM映射基本都是为web项目设计的,与unity项目很难契合,所以我决定自己做一个简易的ORM映射。虽然想的很美但是实际做起来才发现还是挺复杂的,所以我在这里记录一下这次的开发过程,防止以后遗忘。

今天先记录一下如何通过自定义attribute类实现对类名、属性名和关系数据库中的表名、字段名等信息映射。关于attribute类网上资料很多,这里不详细介绍了,下面具体代码中用到的地方会有具体说明。

首先需要自定义三个attribute类,分别是TableAttribute、ColumnAttribute和PrimaryKeyAttribute,这三个类将分别描述表名、字段名和主键名。下面是具体的实现。

1.TableAttribute

  1. using System;
  2. namespace ORM
  3. {
  4. [AttributeUsage(AttributeTargets.Class)]
  5. public class TableAttribute : Attribute
  6. {
  7. public TableAttribute(string tableName)
  8. {
  9. this.Value = tableName;
  10. }
  11. public string Value { get; protected set; }
  12. }
  13. }
2.ColumnAttribute

  1. using System;
  2. namespace ORM
  3. {
  4. [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
  5. public class ColumnAttribute : Attribute
  6. {
  7. public ColumnAttribute(string columnName)
  8. {
  9. this.Value = columnName;
  10. }
  11. public string Value { get; protected set; }
  12. }
  13. }
3.PrimaryKeyAttribute
  1. using System;
  2. namespace ORM
  3. {
  4. [AttributeUsage(AttributeTargets.Class)]
  5. public class PrimaryKeyAttribute : Attribute
  6. {
  7. public PrimaryKeyAttribute(string primaryKey)
  8. {
  9. this.Value = primaryKey;
  10. }
  11. public string Value { get; protected set; }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/253735
推荐阅读
  

闽ICP备14008679号