通过SqlSugar将对象生成数据库
1.对象如下:
[SugarTable("StudentInfo")] // 生成的表名
public class StudentInfo
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] // 主键并且自增长
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Heigh { get; set; }
}
2.生成数据库的操作如下:
string conStr =
"Data Source=192.168.40.13;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=a+0";
ConnectionConfig connConfig = new ConnectionConfig();
connConfig.ConnectionString = conStr;
connConfig.DbType = SqlSugar.DbType.SqlServer;
connConfig.InitKeyType = InitKeyType.Attribute; // ORM生成对象时,通过代码的属性描述生成主键和自增列等信息
// 对象所在的程序集
Assembly assembly = Assembly.LoadFrom("Model.dll");
IEnumerable<Type> types = assembly.GetTypes().Where(c => c.Namespace == "WinFormTest.Model");
bool isBackup = false; //是否备份
using(SqlSugarClient Client = new SqlSugarClient(connConfig))
{
Client.DbMaintenance.CreateDatabase();//创建数据库
if (isBackup)
{
Client.CodeFirst.BackupTable().InitTables(types.ToArray());
}
else
{
Client.CodeFirst.InitTables(types.ToArray());
}
}