SqlSugar 3.实体配置

1.实体使用自带特性

对于CURD来说,只需要配置主键和自增列就行;类的名称和数据库表名不同时,也可设置

1.1 主键自增
[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; }
}
//创建表语句
db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Student));
1.2 多个主键
public class Student
{
    [SugarColumn(IsPrimaryKey = true)] //设置主键
    public Guid  Pk1{ get; set; }
    [SugarColumn(IsPrimaryKey = true)] //设置主键
    public Guid  Pk2{ get; set; }
    public string Name { get; set; }
}
1.3 无主键
public class Student
{
    public Guid  Id{ get; set; }
    public string Name { get; set; }
}
2.实体使用自定义特性
2.1 创建特性的类
    /// <summary>
    /// 自定义类(表)特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true)]
    public class CustomeAttributeClass : Attribute
    {
        //有参构造
        public CustomeAttributeClass(string str)
        {
            testClass = str + "Test";
        }

        public string testClass { get; set; }
    }


   /// <summary>
    /// 自定义属性(列)特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, Inherited = true)]
    public class CustomeAttributeColumn : Attribute
    {
        public CustomeAttributeColumn()
        {
        }

        private string testColumn;

        public string TestColumn
        {
            get { return testColumn; }
            set { testColumn = value; }
        }
    }
2.2 创建带自定义特性的实体类
  [CustomeAttributeClass("At")]
    public class TestModel
    {
        public int Id { get; set; }

        [CustomeAttributeColumn(TestColumn = "Ac")]
        public string Name { get; set; }

        public int Age { get; set; }
    }
2.3在创建SqlSugarClient对象中添加代码
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.MySql,
                ConnectionString = "server = 127.0.0.1; Database = sugarlearn; Uid = root; Pwd = root; AllowLoadLocalInfile = true;",
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,

                //自定义特性
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    //属性(列)的处理
                    EntityService = (property, column) =>
                    {
                        var attributes = property.GetCustomAttributes(true);//get all attributes 

                        if (attributes.Any(it => it is CustomeAttributeColumn))// by attribute set primarykey
                        {
                            column.DbColumnName = (attributes.First(it => it is CustomeAttributeColumn) as CustomeAttributeColumn).TestColumn;
                        }
                    },
                    //类(表)的处理
                    EntityNameService = (type, entity) =>
                    {
                        var attributes = type.GetCustomAttributes(true);

                        if (attributes.Any(it => it is CustomeAttributeClass))
                        {
                            entity.DbTableName = (attributes.First(it => it is CustomeAttributeClass) as CustomeAttributeClass).testClass;
                        }
                    }
                }
            });
2.4添加创建表的代码,查看效果
static void Main(string[] args)
        {
            var db = Sugar.GetInstance();

            //新增表
            db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(TestModel));

            Console.ReadLine();
        }
3.实体不使用特性

创建对象的时候,根据规则,指定哪个字段主键,哪个字段自增;这样就不需要在实体添加特性

var db= new SqlSugarClient(new ConnectionConfig()
{
 DbType = SqlSugar.DbType.MySql,
 ConnectionString = Config.ConnectionString,
 sAutoCloseConnection = 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;
            }
        }
    }
}
});
4.特性明细

下面是CRUD用到的特性,不包含建表的属性

名称描述
IsIdentity自增列
IsPrimaryKey创建主键
ColumnName实体类属性和数据库列名不同时,设置数据库列名
IsIgnoreORM不处理该列 [即忽略]
IsOnlyIgnoreInsert插入操作时不处理该列 [插入时忽略]
IsOnlyIgnoreUpdate更新操作时不处理该列 [更新时忽略]
OracleSequenceName设置Oracle序列,设置后该列等同于自增列
ColumnDescription备注
Length长度
IsNullable是否可以为Null;默认False(允许为NULL)
DecimalDigits精度;decimal(18,2),Length=19,DecimalDigits=2
OldColumnName修改列名用,这样不会新增或删除列
IsDisabledDelete禁止删除列
IsDisabledUpdateAll禁止所有更新表的操作
ColumnDataType字段类型

注意:

  • EntityInfo:关于数据库表的一些属性
  • EntityColumnInfo:关于数据库表字段的一些属性

文档参考:配置实体

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SQLSugar 是一款轻量级ORM框架,它支持自动生成实体类。在 .NET Core 中使用 SQLSugar 自动生成实体类的步骤如下: 1. 安装 SQLSugar 包:在 Visual Studio 中打开 NuGet 包管理器控制台,输入以下命令安装 SQLSugar 包: ``` Install-Package SqlSugar ``` 2. 配置数据库连接字符串:在 appsettings.json 文件中添加数据库连接字符串,例如: ``` "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=MyDatabase;User Id=myUsername;Password=myPassword;" } ``` 3. 创建实体类:在 Models 文件夹中创建一个类,例如: ``` public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } ``` 4. 自动生成实体类:在 Startup.cs 文件的 ConfigureServices 方法中添加以下代码: ``` services.AddScoped<ISqlSugarClient>(c => { var db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Configuration.GetConnectionString("DefaultConnection"), DbType = DbType.SqlServer, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); db.DbFirst.CreateClassFile("Models", "MyNamespace", "MyDatabase"); return db; }); ``` 这段代码会自动生成实体类文件,并保存到 Models 文件夹中。其中,MyNamespace 是你的命名空间,MyDatabase 是你的数据库名称。 5. 使用实体类:在控制器中注入 ISqlSugarClient,然后就可以使用自动生成的实体类了,例如: ``` public class UserController : ControllerBase { private readonly ISqlSugarClient _db; public UserController(ISqlSugarClient db) { _db = db; } [HttpGet] public IActionResult Get() { var users = _db.Queryable<User>().ToList(); return Ok(users); } } ``` 这段代码会查询 User 表中的所有数据,并返回给客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DotNeter-Hpf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值