数据库
首页 > 数据库> > .NET5 SqlSugar 创建数据库表

.NET5 SqlSugar 创建数据库表

作者:互联网

SqlSugar是一款 老牌 .NET 开源ORM框架,.NET中唯一支持自动分表大数据处理的ORM。官网:https://www.donet5.com/Home/Doc

1、添加SqlSugarCore的NuGet包

2、建立实体

新建数据库实体,这里以用户表为例:

public class Users
{
    /// <summary>
    /// ID
    /// </summary>
    [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]//是否为主键,是否自增
    public int Id { get; set; }
    /// <summary>
    /// 用户名
    /// </summary>
    [SugarColumn(ColumnDataType = "varchar(64)")]//对于字符型字段,要指定数据类型
    public string UserName { get; set; }
    /// <summary>
    /// 昵称
    /// </summary>
    [SugarColumn(ColumnDataType = "varchar(128)")]
    public string NickName { get; set; }
    /// <summary>
    /// 手机号
    /// </summary>
    [SugarColumn(ColumnDataType = "varchar(32)")]
    public string Phone { get; set; }
    /// <summary>
    /// 邮箱
    /// </summary>
    [SugarColumn(ColumnDataType = "varchar(64)")]
    public string Email { get; set; }
    /// <summary>
    /// OpenId
    /// </summary>
    [SugarColumn(ColumnDataType = "varchar(32)")]
    public string OpenId { get; set; }
    /// <summary>
    /// 数据提交时间
    /// </summary>
    [SugarColumn(IsOnlyIgnoreUpdate = true)]//在Update的时候忽略该字段
    public DateTime PostTime { get; set; } = DateTime.Now;
}

3、注入SqlSugar

appsettings.json中:配置连接字符串

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "SqlConn": "server=127.0.0.1;port=3306;user=YourUserName;password=YourPassword;database=YourDataBase;"
}

Startup.cs类中:

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllersWithViews();
     #region SqlSugarIOC
         services.AddSqlSugar(new IocConfig()
		 {
				 ConnectionString = this.Configuration["SqlConn"],
				 DbType = IocDbType.MySql,
				 IsAutoCloseConnection = true,
		 });
     #endregion
 }

4、创建表

/// <summary>
/// 创建数据库表
/// </summary>
public void CreateTable()
{
    // 创建数据库
    base.Context.DbMaintenance.CreateDatabase();
    // 创建表
    base.Context.CodeFirst.InitTables(
        //创建的四个表
        typeof(Models.Users),
        typeof(Models.SearchEngines),
        typeof(Models.SearchLogs),
        typeof(Models.UrlTags)
    );
}

来源:https://www.blackvon.cn/#/detail?id=125&uid=1

标签:set,varchar,get,数据库,ColumnDataType,SugarColumn,NET5,public,SqlSugar
来源: https://blog.csdn.net/weixin_42281203/article/details/121210391