/// <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();
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有