1.索引穿件首先需要标记好相应的类
通过添加属性来标记
///索引部分
namespace Zzy.SqlSugar.Models
{
[SugarIndex("test1_Index_SqlSugarIndex_name", nameof(Name), OrderByType.Asc)] //普通索引--非聚集索引
[SugarIndex("test2_Unique_SqlSugarIndex_CreateTime", nameof(CreateTime), OrderByType.Desc, true)] //唯一索引 (true表示唯一索引)
[SugarIndex("test3_Index_SqlSugarIndex_nameid", nameof(Name), OrderByType.Asc, nameof(CodeFirstTable1.Id), OrderByType.Desc)] //复合普通索引
[SugarIndex("test4_{db}index_SqlSugarIndex_name", nameof(Description), OrderByType.Asc)] //使用 {db} 进行占位符替换,小写不要有空格
[SugarIndex("test5_Index_{table}_name", nameof(DescriptionNew), OrderByType.Asc)] //表名占位符(自动分表不需要加这个自动的)
[SugarIndex("test6_IndexUnituadfasf3_longx{include:name,id}", nameof(IndexUnituadfasf), OrderByType.Asc)]
[SugarTable("SqlSugarIndex", TableDescription = "表备注")]//表添加备注
public class SqlSugarIndex
{
[SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
public int Id { get; set; }
public string? Name { get; set; }
[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom
public string? Text { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime CreateTime { get; set; }
[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom
public string? Description { get; set; }
[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom
public string? DescriptionNew { get; set; }
[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom
public string? IndexUnituadfasf { get; set; }
}
}
2.接着创建表就会自动将索引创建
public static void CodeFirstIndexShow()
{
ConnectionConfig connectionConfig= new ConnectionConfig();
connectionConfig.ConnectionString = SqlSugarConnectionString.GetConnectionString1();
connectionConfig.IsAutoCloseConnection= true;
connectionConfig.DbType = DbType.SqlServer;
using (SqlSugarClient sqlSugarClient = new SqlSugarClient(connectionConfig))
{
if (sqlSugarClient.DbMaintenance.IsAnyTable("SqlSugarIndex"))
{
sqlSugarClient.DbMaintenance.DropTable("SqlSugarIndex");
}
sqlSugarClient.CodeFirst.InitTables(typeof(SqlSugarIndex));
}
}