C#实现根据实体类自动创建数据库表
作者:天碼行空 发布时间:2024-01-12 13:23:29
标签: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();
}
}
}
}
从上边代码可以看出来,特性本身也是类,继承自Attribute类,我们可以对类、方法、属性等元素进行特性标注
上边是一个简单示例,我们可以通过自定义[DbKey]特性,标注在需要设置主键的字段上
需要动态创建数据库的时候,可以从实体类中解析出表名、字段名、主键字段、字段说明等等,然后生成创建数据库表的脚本,动态创建数据库表
创建数据库的代码,后边可以进一步补充
来源:http://www.cnblogs.com/jh007/p/6124179.html


猜你喜欢
- 可以用函数 json.dumps()将 Python 对象编码转换为字符串形式。例如:import json python_obj = [[
- 实例如下:</pre><pre name="code" class="python"
- 近期在使用bootstrap这个优秀的前端框架,这个框架非常强大,框架里面有下
- 有时候系统会以pytest的形式运行,如果不想以这种方式运行,换回普通模式,那么就点击画圈圈那里的白色三角行点击Edit configura
- 1.复制表结构及数据到新表CREATE TABLE 新表SELECT * FROM 旧表 2.只复制表结构到新表CREATE TABLE 新
- mysql 8.0.28版本安装配置方法图文教程,供大家参考,具体内容如下从 Mysql 官网下载 mysql 或直接点击这里下载下载完成后
- 时间序列预测时间序列是按照时间顺序排列的数据集合,在很多应用中都非常常见。时间序列分析是对这些数据进行分析和预测的过程。时间序列预测是该分析
- 首先看这下面的例子(鼠标移上去):<TABLE><TBODY><TR&g
- 以下工具类代码来自开源项目pyslam。Timerimport cv2 class Colors(object): &
- 本文针对MySQL数据库基本操作进行学习研究,需要了解的朋友不要错过这篇文章。以下均是在Windows 64位操作系统下的命令行使用。学习之
- 项目总体情况软件:Pycharm环境: Python 3.7.9(考虑到客户可能会有不同操作系统,为了兼容性考虑)技术库: requests
- 最近公司产品和百度贴吧合作搞活动,为了增加人气,打算做个自动签到的小程序。这个是测试登录的代码,写的比较随意,仅实现了登录并读取关注贴吧列表
- 自开始做项目以来,一直在用。这段存储过程的的原创者(SORRY,忘记名字了),写得这段SQL代码很不错,我在这个基础上,按照我的习惯以及思维
- [LeetCode] 185.Department Top Three Salaries 系里前三高薪水The Employee&
- <img :onerror="errpic" class="customerHead" :sr
- 类属性和对象属性我们把定义在类中的属性称为类属性,该类的所有对象共享类属性,类属性具有继承性,可以为类动态地添加类属性。对象在创建完成后还可
- 1.概念百度百科:笛卡尔乘积是指在数学中,两个集合X和Y的笛卡尔积(Cartesian product),又称直积,表示为X &ti
- codecs在读取文件时,发生错误:UnicodeDecodeError: 'utf-8' codec can't
- 习惯于使用数据库之前都必须创建一个连接池,即使是单线程的应用,只要有多个方法中需用到数据库连接,建立一两个连接的也会考虑先池化他们。连接池的
- replace 方法返回根据正则表达式进行文字替换后的字符串的复制。stringObj.replace(rgExp, replaceText