
1、创建表
中间标准:
|
5.1.3.44-preview06 推荐 |
|
| string 设置长度的字符串 |
[SugarColumn(Length=10] |
| int 整数 |
public int FieldName{ get; set; } |
| short 整数小 | |
| long 大数字 |
public long FieldName{ get; set; } |
| bool 真假 | |
| decimal 默认 |
public decimal FieldName{ get; set; } |
| decimal 自定义 |
//18,2 18,4 18,6 这几种兼容性好 public decimal FieldName{ get; set; } |
| DateTime 时间 |
public DateTime FieldName{ get; set; } |
| 枚举 (数据库存int) | |
| byte[] 二进制 |
public byte[] FileInfo{get;set;} 对多库支持了比较好 |
DbType = SqlSugar.DbType.SqlServer, ConnectionString ="字符串",
IsAutoCloseConnection = true,
|
1.1通过特性建表
public class CodeFirstTable1
{
[SugarColumn(IsIdentity = true, IsPrimaryKey = true]
public int Id { get; set; }
public string Name { get; set; }
//ColumnDataType 自定格式的情况 length不要设置 (想要多库兼容看4.2和9)
[SugarColumn(ColumnDataType = "Nvarchar(255"]
public string Text { get; set; }
[SugarColumn(IsNullable = true]//可以为NULL
public DateTime CreateTime { get; set; }
}
/***创建单个表***/
db.CodeFirst.SetStringDefaultLength(200.InitTables(typeof(CodeFirstTable1;//这样一个表就能成功创建了
/***手动建多个表***/
db.CodeFirst.SetStringDefaultLength(200
.InitTables(typeof(CodeFirstTable1,typeof(CodeFirstTable2;
建表特性如下
| 名称 | 描述 |
|---|---|
| IsIdentity | 是否创建自增标识 |
| IsPrimaryKey | 是否创建主键标识 |
| ColumnName | 创建数据库字段的名称(默认取实体类属性名称) |
| ColumnDataType |
用法1: “varchar(20” 不需要设置长度 用法3: 多库兼容可以用 :看标题9 |
| IsIgnore | ORM不处理该列 |
| ColumnDescription | 备注 表注释 (新版本支持XML文件) |
| Length | 长度 设成10会生成 xxx类型(10, 没括号的不设置 |
| IsNullable | 是否可以为null默为false |
| DecimalDigits | 精度 如 decimal(18,2 length=18,DecimalDigits=2 |
| OracleSequenceName | 设置Oracle序列,设置后该列等同于自增列 |
| OldColumnName | 修改列名用,这样不会新增或者删除列 |
| IndexGroupNameList | 已弃用,新用法看文档4.3 |
| UniqueGroupNameList | 已弃用,新用法看文档4.3 |
|
DefaultValue |
DefaultValue=默认值 用来建表设置字段默认值 很多情况需要2个一起使用 如果建表并且插入数据用2个 |
2.2无特性建表
如果我们的实体不需要加特性,那么我们可以通过特性方式建表
SugarClient db = new SqlSugarClient(new ConnectionConfig(
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString3,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices(
{
EntityService = (s, p =>
{
//如果是Order实体进行相关配置
p.IfTable<Order>(
.UpdateProperty(it => it.id, it =>
{
it.IsIdentity = true;
it.IsPrimarykey = true;
}
.UpdateProperty(it => it.Name, it => {
it.Length = 100;
it.IsNullable = true;
}
.OneToOne(it => it.Item, nameof(Order.ItemId;
//如果Custom实体进行相关配置
p.IfTable<Custom>(
.UpdateProperty(it => it.id, it =>
{
it.IsIdentity = true;
it.IsPrimarykey = true;
}
.UpdateProperty(it => it.Text, it => {
it.DataType= StaticCo