当表与实体名不相同的时候或者我们用到Schema(Schema需要升级到4.6.0.4)的时候,我们有三种方式实现Mapping
1.实体特性
[SugarTable("ado.Student")] //别名处理
public class Student {
[SugarColumn(IsIgnore=true)]
public string xxx{get;set;} //这列在ORM会过滤掉
[SugarColumn(ColumnName="name")]
public string xxx{get;set;} //这列在ORM会当成 name处理
}说明:
1.ColumnName 定义数据库表字段的真实名称,当一样的时候可以不定义该特性
2.IsIgnore 查询 增加 删除 更新会过滤这一列,如果想让查询也有这一列可以用.Select("*")强制查所有列
3.IsPrimaryKey 标识是否为主键,更新和插入的时候会根据主键值判段更新哪条,当InitKey为Attribute时一定要加该特性不然找不到主键,Systemtable加了没有效果
4.IsIdentity 是否为自增长 ,更新和插入的时候会根据会有用,当InitKey为Attribute时一定要加该特性,Systemtable加了没有效果
5.ColumnDescription 列描述,暂时未实现该功能
6.Length 长度,生成表会用到
7.IsNullable 是否可空,生成表会用到
8.OldColumnName 修改列名,生成表会用到
9.ColumnDataType 自定义生成的数据类型,生成表会用到
更多:
http://www.donet5.com/Doc/8/1141
2.属性是死的所以提供了动态方式
注意:Add里面传的是实体名和实体属性名称,不是表名和字段名注意!
db.MappingTables.Add() 别名表 db.MappingColumns.Add() 别名列 db.IgnoreColumns.Add() 过滤列
3.As方式
//表
Queryable<T>().As("newName") //select * from newName
Insertable
Updateable
Deleteable
//列
.Where(it=>SqlFunc.MappingColumn(it.OldName,"NewName") == "jack")优先级:
AS>属性>动态
4使用自定义特性
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; }
}2016 © donet5.comApache Licence 2.0