SqlSugar实体

1、实体使用自带特性

 1.1 使用用例

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

主键自增

[SugarTable("dbstudent")]//当和数据库名称不一样可以设置表别名 指定表明
public class Student
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//数据库是自增才配自增 
    public int Id { getset; }
    public int? SchoolId { getset; }
    [SugarColumn(ColumnName ="StudentName")]//数据库与实体不一样设置列名 
    public string Name { getset; }
}

双主键、复合主键、联合主键、多个主键

表中字段 如果是自增需要加上 IsIdentity,否则不需要

public class Student
{
    [SugarColumn(IsPrimaryKey = true)] //设置主键
    public Guid  Pk1{ getset; }
    [SugarColumn(IsPrimaryKey = true)] //设置主键
    public Guid  Pk2{ getset; }
    public string Name { getset; }
}

无主键

当表中无主键的时候更新和删除,需要指定条件,具体用法看文档

public class Student
{
    public Guid  Id{ getset; }
    public string Name { getset; }
}

总结:只需要针对数据库中的 自增和主键进行设置即可,和数据库一致

 1.2 特性明细

下面是CRUD用到的特性,不包含建表的属性 (建表看文档【迁移】)

IsIdentity

自增列

如果是Oracle请设置OracleSequenceName 设置后和自增一样使用

IsPrimaryKey 创建主键
ColumnName 实体类数据库列名不一样设置数据库列名
IsIgnore

IsIgnore=true表示 ORM 所有操作不处理这列

一般用于数据库没有这一列

ORM 非数据库列加上该特性(配置导航查询自动IsIgnore=true)

IsOnlyIgnoreInsert 插入操作时不处理该列 【插入中忽略】 对数据库默认值有效
IsOnlyIgnoreUpdate

更新操作不处理该列 【更新中忽略】

InsertServerTime  插入操作:true数据库时间
UpdateServerTime  更新操作:true数据库时间
InsertSql

插入根据SQL

 等于"0"插入0 

 等 于"'a'" 插入a

 等于 "newid()" 插入newid()

UpdateSql

 更新根据SQL

 等于"0"更新0 

 等 于"'a'" 更新a

 等于 "newid()" 更新newid()

QuerySql

5.1.4.128+

用于单表查询在没有使用Select下根据Sql生成

例如等于" Cast( Num_float64 as varchar(500))"

生成的Sql :  Cast( Num_float64 as varchar(500)) AS Num_float64 

一般用于orm驱动不支持的类型并且自定义类型也失效的情况

只在单表查询,不使用Select的情况下才生效

注意:

联表或者SELECT使用  函数或者扩展函数实现

OracleSequenceName 设置Oracle序列,设置后该列等同于自增列
MaxParameterNameLength 一般等于30,用于处理Oracle11 :参数化名字和索引名字超过30

建表看文档【迁移】,这边只介绍CRUD用到的属性

 

2、实体使用自定义特性

下面是实现自定义特性的例子

SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = Config.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;
            }
        }
    }
});
 
[Table("student")]
//[SugarTable("student")]
public class MyStudent
{
 
    [Key]
    //[SugarColumn(IsPrimaryKey =true)]
    public string Id { getset; }
    public string Name { getset; }
}

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

 

分享你们的自定义特性实现:

1、方便其它人使用

2、方便自已使用

分享地址: http://www.donet5.com/Ask/9/11065

 

 

3、实体不使用特性

3.1 无封装写法

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

var db= new SqlSugarClient(new ConnectionConfig()
{
 DbType = SqlSugar.DbType.MySql,
 ConnectionString = Config.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;
            }
        }
    }
    ,
    EntityNameService = (type, entity) =>
     {
      //entity.DbTableName 修改表名
     }
}
});
//根据你自个的逻辑去设置相应的主键和自增,也可以从数据库读出主键和自增来动态设置
//db.DbMaintenance.GetColumnInfosByTableName 可以拿到表的信息

3.2 语法糖(5.1.45)

如果大量if else比较难看所以针对指定表进行了一些封

SqlSugarClient 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= StaticConfig.CodeFirst_BigString;//支持多库的MaxString用法
              })
             
                         
            //好处就是配置导航方便,和针对指定表设置会方便些
            //可以结合全局逻辑一起使用,如果下面逻辑和上面有冲突,下面的会覆盖上面的
              
             
            //统一设置 nullable等于isnullable=true
             if(p.IsPrimaryKey==false&&new NullabilityInfoContext()
                         .Create(c).WriteState is NullabilityState.Nullable)
             {
                           p.IsNullable = true;
             }
              
              
              
        },
        EntityNameService = (type, entity) =>
        {
           //entity.DbTableName 修改表名
        }
    }
});
//性能说明:
//EntityService 相同实体只会执行一次性不需太操作

 

4、迁移-建表

public class CodeFirstTable1
{
        [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
        public int Id { getset; } 
        public string Name { getset; }
        //ColumnDataType 一般用于单个库数据库,如果多库不建议用
        [SugarColumn(ColumnDataType = "Nvarchar(255)")]
        public string Text { getset; }
        [SugarColumn(IsNullable = true)]//可以为NULL
        public DateTime CreateTime { getset; }
}
  
//建表
db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1));
posted @ 2024-01-16 15:37  yswenli  阅读(342)  评论(0编辑  收藏  举报