发布:2022/1/4 14:07:13作者:管理员 来源:本站 浏览次数:1410
新建数据库实体,这里以用户表为例:
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)
);
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4