当前位置:首页 > 通信资讯 > 正文

c#实体类建数据库表结构(C#创建数据库)

.Net新手通常容易把属性(Property)跟特性(Attribute)搞混,其实这是两种不同的东西

属性指的类中封装的数据字段;而特性是对类、字段、方法和属性等元素标注的声明性信息

如下代码(Id、Name为User的属性,[DbKey]为Id的特性)

?
1 2 3 4 5 6 7 8 9 /// <summary> /// 用户信息 /// </summary> public class User { [DbKey] public string Id { get; set; } public string Name { get; set; } }

特性分预定义特性和自定义特性,本节主要讲述自定义特性

特性能解决什么问题?

假如现在需要通过定义一些实体类,动态创建出对应的数据库表,该怎么做呢?

直接上代码

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 namespace CustomerAttribute { /// <summary> /// 数据库主键 /// </summary> public class DbKey : Attribute { public string Description { get; set; } public DbKey() { } public DbKey(string description) { this.Description = description; } } }
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 namespace CustomerAttribute { /// <summary> /// 用户信息 /// </summary> public class User { [DbKey] public string Id { get; set; } public string Name { get; set; } } /// <summary> /// 用户角色 /// </summary> public class UserRole { [DbKey("用户ID")] public string UserId { get; set; } [DbKey("角色ID")] public string RoleId { get; set; } } }
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 namespace CustomerAttribute { class Program { /// <summary> /// 获取数据库主键字段 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> private static IEnumerable<PropertyInfo> getDbKeyFields<T>() { // 获取当前类中的公共字段 var fields = typeof(T).GetProperties(); // 查找有DbKey特性的字段 var keyFields = fields.Where(field => (DbKey)Attribute.GetCustomAttribute(field, typeof(DbKey)) != null); return keyFields; } private static string getDescription(PropertyInfo field) { string result = string.Empty; var dbKey = (DbKey)Attribute.GetCustomAttribute(field, typeof(DbKey)); if (dbKey != null) result = dbKey.Description; return result; } static void Main(string[] args) { try { var userKeyFields = getDbKeyFields<User>(); Console.WriteLine("User表的主键为:" + string.Join(",", userKeyFields.Select(field => field.Name))); var userRoleKeyFields = getDbKeyFields<UserRole>(); Console.WriteLine("UserRole表的主键为:" + string.Join(",", userRoleKeyFields.Select(field => field.Name))); foreach (PropertyInfo field in userRoleKeyFields) { string description = getDescription(field); Console.WriteLine(string.Format("{0}字段的描述信息为:{1}", field.Name, description)); } } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } }

从上边代码可以看出来,特性本身也是类,继承自Attribute类,我们可以对类、方法、属性等元素进行特性标注

上边是一个简单示例,我们可以通过自定义[DbKey]特性,标注在需要设置主键的字段上

需要动态创建数据库的时候,可以从实体类中解析出表名、字段名、主键字段、字段说明等等,然后生成创建数据库表的脚本,动态创建数据库表

创建数据库的代码,后边可以进一步补充

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://www.cnblogs.com/jh007/p/6124179.html

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。