当我们数据库插入和更新的时候,ORM需要知道主键和自增列,我们有2种方式获取,一种直接从数据库表中读取,还有一种从实体特性中读取。一般我们建议从特性读取,因为这样不需要考虑一些特殊情况(例如一些库的特殊设置读不到)
[SugarTable("dbstudent")]//当和数据库名称不一样可以设置别名 public class Student { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//通过特性设置主键和自增列 public int Id { get; set; } public int? SchoolId { get; set; } [SugarColumn(ColumnName ="StudentName")]//数据库列名取自定义 public string Name { get; set; } } var config = new ConnectionConfig() { DbType = DbType.MySql, ConnectionString = "", IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute //设置读特性 };
var config = new ConnectionConfig() { DbType = DbType.MySql, ConnectionString = "", IsAutoCloseConnection = true, InitKeyType = InitKeyType.SystemTable//设置从数据库表 }; //实体不需要特性 public class Student { public int Id { get; set; } public int? SchoolId { get; set; } public string Name { get; set; } }
名称 | 描述 |
---|---|
IsIdentity | 自增列 如果是Oracle请设置OracleSequenceName 设置后和自增一样使用 |
IsPrimaryKey | 创建主键 |
ColumnName | 实体类数据库列名不一样设置数据库列名 |
IsIgnore | ORM不处理该列 |
IsOnlyIgnoreInsert IsOnlyIgnoreUpdate | 插入操作时不处理该列 更新操作不处理该列 |
ColumnDescription | 备注 |
Length | 长度 |
IsNullable | 是否可以为null默为false |
DecimalDigits | 精度 如 decimal(18,2) length=18,DecimalDigits=2 |
OracleSequenceName | 设置Oracle序列,设置后该列等同于自增列 |
OldColumnName | 修改列名用,这样不会新增或者删除列 |
IndexGroupNameList | 创建索引用 |
下面是实现自定义特性的例子
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute, 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; } }, 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; } } } }); [Table("student")] //[SugarTable("student")] public class MyStudent { [Key] //[SugarColumn(IsPrimaryKey =true)] public string Id { get; set; } public string Name { get; set; } }
该功能非常强大远不止这点用法,可以统一处理一些特性逻辑
1、方便其它人使用
2、方便自已使用
分享地址: http://www.donet5.com/Ask/9/11065
2016 © donet5.comApache Licence 2.0