C# 經過自定義特性 完成依據實體類自動創立數據庫表。本站提示廣大學習愛好者:(C# 經過自定義特性 完成依據實體類自動創立數據庫表)文章只能為提供參考,不一定能成為您想要的結果。以下是C# 經過自定義特性 完成依據實體類自動創立數據庫表正文
.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();
}
}
}
}
View Code
從上邊代碼可以看出來,特性自身也是類,承繼自Attribute類,我們可以對類、辦法、屬性等元素停止特性標注
上邊是一個復雜示例,我們可以經過自定義[DbKey]特性,標注在需求設置主鍵的字段上
需求靜態創立數據庫的時分,可以從實體類中解析出表名、字段名、主鍵字段、字段闡明等等,然後生成創立數據庫表的腳本,靜態創立數據庫表
創立數據庫的代碼,後邊可以進一步補充