Code First是通过实体生成表,定义实体很简单
属性介绍
我们会根据字段的属性生成数据库字段
IsNullable表示表字段是否可空
IsIgnore 为true表示不会生成字段到数据库
IsIdentity表示为自增列
IsPrimaryKey表示为主键
Length 表示字段长度
DecimalDigits 表示字段的精度 4.4
ColumnDataType 强制设置数据库字段的类型(考虑到切换数据库有些类型其它库没有最新版本支持多个以逗号隔离,比如=“number,int”)
Code First模式目前只支持单主键
public class CodeTable
{
[SugarColumn(IsNullable =false ,IsPrimaryKey =true,IsIdentity =true)]
public int Id { get; set; }
[SugarColumn(Length = 21)]
public string Name{ get; set; }
[SugarColumn(IsNullable = true)]
public bool IsOk { get; set; }
public Guid Guid { get; set; }
public decimal Decimal { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime? DateTime { get; set; }
[SugarColumn(IsNullable = true)]
public double? Dob2 { get; set; }
[SugarColumn(Length =10)]
public string A { get; set; }
}public class CodeTable2 {
public int Id { get; set; }
public string Name { get; set; }
[SugarColumn(IsIgnore =true)]
public string TestId { get; set; }
}使用CodeFirst 要将InitKeyType设为Attribute
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});InitTables函数是将实体转换成数据库表
生成表,并且修改类会备份 例如表A,备份表名为 A+时间
db.CodeFirst.BackupTable().InitTables(typeof(CodeTable),typeof(CodeTable2));
生成表不会备份表
db.CodeFirst.InitTables(typeof(CodeTable),typeof(CodeTable2));
给varchar设置默认长度
db.CodeFirst.SetStringDefaultLength(10).InitTables(typeof(CodeTable),typeof(CodeTable2));
如果实体属性名称为Name我要将Name改成NewName
我们只需要修改实体
[SugarColumn(Length = 21,OldColumnName = "Name")]
public string NewName{ get; set; }然后执行InitTables便可,注意如果不这样操作,会将原有列删除创建新列
2016 © donet5.comApache Licence 2.0