国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#實現根據實體類自動創建數據庫表

2019-10-29 21:17:06
字體:
來源:轉載
供稿:網友

.Net新手通常容易把屬性(Property)跟特性(Attribute)搞混,其實這是兩種不同的東西

屬性指的類中封裝的數據字段;而特性是對類、字段、方法和屬性等元素標注的聲明性信息

如下代碼(Id、Name為User的屬性,[DbKey]為Id的特性)

/// <summary>/// 用戶信息/// </summary>public class User{ [DbKey] public string Id { get; set; } public string Name { get; set; }}

特性分預定義特性和自定義特性,本節主要講述自定義特性

特性能解決什么問題?

假如現在需要通過定義一些實體類,動態創建出對應的數據庫表,該怎么做呢?

直接上代碼

namespace CustomerAttribute{ /// <summary> /// 數據庫主鍵 /// </summary> public class DbKey : Attribute { public string Description { get; set; } public DbKey() { } public DbKey(string description) {  this.Description = description; } }}
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; } }}
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]特性,標注在需要設置主鍵的字段上

需要動態創建數據庫的時候,可以從實體類中解析出表名、字段名、主鍵字段、字段說明等等,然后生成創建數據庫表的腳本,動態創建數據庫表

創建數據庫的代碼,后邊可以進一步補充

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VEVB武林網!


注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金乡县| 卢龙县| 齐齐哈尔市| 青州市| 子长县| 咸宁市| 合阳县| 黔西县| 洛宁县| 太白县| 郧西县| 定安县| 金平| 开封市| 四子王旗| 南川市| 虞城县| 阿荣旗| 阿克| 洪江市| 东平县| 榆林市| 江口县| 军事| 武胜县| 元氏县| 利川市| 玛纳斯县| 东乡县| 鹤庆县| 博爱县| 五峰| 霍林郭勒市| 长武县| 漯河市| 大冶市| 松滋市| 谢通门县| 华池县| 衡南县| 大厂|