第三章:数据模型与数据库设计
博客v1.0系列教程(Csharp)博客 v1.0 系列教程 (C#)
3.1 数据库整体设计
博客系统包含 13 张核心表,涵盖用户、文章、评论、收藏、日志等模块。
用户表 (user_models)
[SugarTable("user_models")]
public class UserModel
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public long Id { get; set; }
public string? Username { get; set; }
public string? Password { get; set; } // BCrypt 哈希
public string? Nickname { get; set; }
public string? Email { get; set; }
public short? Role { get; set; } // 0:普通 1:管理员
public string? Ip { get; set; }
public string? Location { get; set; }
public DateTime? CreateTime { get; set; }
}
文章表 (article_models)
[SugarTable("article_models")]
public class ArticleModel
{
public long Id { get; set; }
public string? Title { get; set; }
public string? Content { get; set; } // Markdown 内容
public string? Category { get; set; }
public string? Tags { get; set; } // JSON 数组
public string? Status { get; set; } // draft/published
public int? DiggCount { get; set; }
public int? CommentCount { get; set; }
public int? ViewCount { get; set; }
public long? UserId { get; set; }
public DateTime? CreateTime { get; set; }
}
评论表 (comment_models)
[SugarTable("comment_models")]
public class CommentModel
{
public long Id { get; set; }
public string? Content { get; set; }
public long? ArticleId { get; set; }
public long? UserId { get; set; }
public long? ParentId { get; set; } // 父评论
public long? RootParentId { get; set; } // 根评论
public int? DiggCount { get; set; }
public DateTime? CreateTime { get; set; }
}
其他表
- collect_models: 收藏夹
- user_article_collect_models: 文章-收藏关联
- article_digg_models: 文章点赞
- user_article_look_history_models: 浏览历史
- user_conf_models: 用户配置
- site_configs: 站点配置(JSON 持久化)
- log_models: 审计日志
- global_notications: 全局通知
- banner_models: 轮播图
3.2 SqlSugar 配置
public class DbContext
{
public static SqlSugarClient GetClient(string connectionString)
{
return new SqlSugarClient(new ConnectionConfig
{
ConnectionString = connectionString,
DbType = DbType.PostgreSQL,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
}
3.3 数据迁移
SqlSugar 支持 CodeFirst 自动建表:
using (var db = DbContext.GetClient(connectionString))
{
db.CodeFirst.InitTables(
typeof(UserModel),
typeof(ArticleModel),
typeof(CommentModel)
// ... 其他实体
);
}
下一章将实现仓储模式与工作单元。
csharpdatabasesqlsugarpostgresql