连接字符串
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
InitKeyType = InitKeyType.SystemTable //初始化主键和自增列信息到ORM的方式
});InitKeyType 是读取主键和自增列信息的方式,配置不正确ORM更新、插入、根据主键查询等情况就会有找不到主键等错误
SystemTable 从数据库系统表查询,这种需要SA这种高权限账号,对纯MODEL有洁癖的用户适用
Attribute 不受数据库限制通过实体特性读取,如果找不到主键什么的都改用Attribute方式老老实实给实体加特性
InitKeyType.SystemTable定义实体
public class School
{
public int Id { get; set; }
public string Name { get; set; }
public string Description{get;set;}
}InitKeyType.Attribute定义实体
public class School
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] //是主键, 还是标识列
public int Id { get; set; }
public string Name { get; set; }
public string Description{get;set;}
}2.结构不一样的情况
我们就需要定义别名进来Mapping
InitKeyType.SystemTable
[SugarTable("ORM_School")] //对应数据库的ORM_School表
public class School
{
public int Id { get; set; }
public string Name { get; set; }
[SugarColumn(ColumnName ="Remark")]
public string Description { get; set; }
}InitKeyType.Attribute
[SugarTable("ORM_School")] //对应数据库的ORM_School表
public class School
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] //是主键, 还是标识列
public int Id { get; set; }
public string Name { get; set; }
[SugarColumn(ColumnName ="Remark")] //对应表里面的Remark列
public string Description { get; set; }
}3.动态定义别名
我们可以用Add的方式
db.MappingTables.Add("实体类名称", "数据库表明");
db.MappingColumns.Add("实体类属性名称", "数据库表里面的列名", "实体类名称");
db.IgnoreColumns.Add("实体类属性名称", "实体类名称");我们还可以用AS
//别名表
db.Queryable<T>().As("tableName").ToList();
//别名列
.Where(it=>SqlFunc.MappingColumn(it.OldName,"NewName") == "jack")他们之间的优先级:
AS>Add>属性方式
4.自定义实体特性
很多人不想在实体里面添加SqlSugar.dll所以我们也支持了自定义特性支持
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() {
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
ConfigureExternalServices=new ConfigureExternalServices() {
EntityService = (property, column) => {
if (property.Name == "xxx") {//根据列名
column.IsIgnore = true;
}
var attributes = property.GetCustomAttributes(true);//get all attributes
if (attributes.Any(it => it is KeyAttribute))//根据自定义属性
{
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(Name ="student")]//default
public class StudentTest {
[Key]
public string Id { get; set; }
public string xxx { get; set; }
public string Name { get; set; }
}给实体取真实的表名,一样的时候可以不加该特性
[SugarTable("STudent")]多个以逗号格开
[SugarColumn(IsIgnore=true)]
1.ColumnName 定义数据库表字段的真实名称,当一样的时候可以不定义该特性
2.IsIgnore 不作数据库操作,true将不会进行查询、添加等操作
3.IsPrimaryKey 标识是否为主键,更新的时候会根据主键值判段更新哪条,当InitKey为Attribute时一定要加该特性不然找不到主 键
4.IsIdentity 是否为自增长
5.ColumnDescription 列描述
6.Length 长度,生成表会用到
7.IsNullable 是否可空,生成表会用到
8.OldColumnName 修改列名,生成表会用到
9.ColumnDataType 自定义生成的数据类型,生成表会用到
2016 © donet5.comApache Licence 2.0