0%

SqlSugar 配置实体

配置实体属性

使用自带特性

对于 CRUD 来说只需要配置主键和自增列就行了,如果类的名称和数据库不一样可以设置数据库中的名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 当和数据库名称不一样可以设置表别名 指定表明
[SugarTable("user_info")]
public class Users
{
// 数据库是自增才配自增
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }

// 数据库与实体不一样设置列名
[SugarColumn(ColumnName ="user_name")]
public string Name { get; set; }

public int? Age { get; set; }
}
IsIdentity 是否创建自增标识
如果是 Oracle 请设置 OracleSequenceName 设置后和自增一样使用
OracleSequenceName 设置 Oracle 序列,设置后该列等同于自增列
IsPrimaryKey 是否创建主键标识
ColumnName 创建数据库字段的名称(默认取实体类属性名称)
IsIgnore IsIgnore=true 表示 ORM 所有操作不处理这列
一般用于数据库没有这一列
ORM 非数据库列加上该特性(配置导航查询自动 IsIgnore=true)
Length 长度 设成 10 会生成 xxx 类型 (10), 没括号的不设置
IsNullable 是否可以为 null 默为 false
DecimalDigits 精度 如 decimal(18,2) length=18,DecimalDigits=2
OldColumnName 修改列名用,这样不会新增或者删除列
IndexGroupNameList 创建索引用
UniqueGroupNameList 创建唯一索引
IsOnlyIgnoreInsert
IsOnlyIgnoreUpdate
插入操作时不处理该列 【插入中忽略】
更新操作不处理该列 【更新中忽略】
可以结合使用

使用自定义特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = configuration.ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
EntityService = (property, column) =>
{
var attributes = property.GetCustomAttributes(true);//get all attributes

if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey
{
column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细
}
//可以写多个,这边可以断点调试
// if (attributes.Any(it => it is NotMappedAttribute))
//{
// column.IsIgnore= true;
//}
},
EntityNameService = (type, entity) =>
{
var attributes = type.GetCustomAttributes(true);
if (attributes.Any(it => it is TableAttribute))
{
entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name;
}
}
}
});

该功能非常强大远不止这点用法,可以统一处理一些特性逻辑

不使用特性

根据规则来设置哪个是主键,哪个是自增,这样就不需要在实体加特性了 (SqlSugar 只需主键和自增就可以完成所有操作)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var db= new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = configuration.ConnectionString,
IsAutoCloseConnection = true,
ConfigureExternalServices=new ConfigureExternalServices() {
EntityService = (t, column) =>
{
if (column.PropertyName.ToLower() == "id") //是 id 的设为主键
{
column.IsPrimarykey = true;
if (column.PropertyInfo.PropertyType == typeof(int)) //是 id 并且是 int 的是自增
{
column.IsIdentity = true;
}
}
}
}
});
//根据你自个的逻辑去设置相应的主键和自增,也可以从数据库读出主键和自增来动态设置
//db.DbMaintenance.GetColumnInfosByTableName 可以拿到表的信息

参考 SqlSugar 官方文档

欢迎关注我的其它发布渠道