.Net 5.0 EFCore (一)
Jayden‘s Blog
2023年03月20日 · 阅读 676
安装Nuget包
IDE使用的是Visual Studio 2019,使用的EF版本是5.0.17,数据库用的SqlServer
Install-package Microsoft.EntityFrameworkCore -Version 5.0.17
Install-package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.17
创建DB上下文
上下文实体
public class BlogContext : DbContext
{
public BlogContext(DbContextOptions<BlogContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(ConfigHelper.GetSectionValue("DbConnection"));
public DbSet<TagEntity> Tags { get; set; }
public DbSet<UserEntity> Users { get; set; }
public DbSet<ArticleEntity> Articles { get; set; }
public DbSet<ArticleDetailEntity> ArticleDetails { get; set; }
public DbSet<ArticleTagEntity> ArticleTags { get; set; }
}
实体基类
public class BaseEntity
{
/// <summary>
/// 主键Id
/// </summary>
[Key]
[MaxLength(60)]
public string Id { get; set; }
/// <summary>
/// 添加时间
/// </summary>
public DateTime CreateTime { get; set; } = DateTime.Now;
/// <summary>
/// 是否删除
/// </summary>
public int IsDel { get; set; } = 0;
}
用户实体
public class UserEntity : BaseEntity
{
/// <summary>
/// 用户名
/// </summary>
[MaxLength(50)]
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public int Gender { get; set; } = 1;
}
文章实体
public class ArticleEntity : BaseEntity
{
/// <summary>
/// 用户id
/// </summary>
public string UserId { get; set; }
/// <summary>
/// 文章标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 概要
/// </summary>
public string Summary { get; set; }
/// <summary>
/// 封面图
/// </summary>
public string Poster { get; set; }
}
省略其他实体的创建描述…
使用数据迁移创建数据库
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0.17
Add-Migration InitDB
Update-Database
如图,其中Migrations文件加中为数据迁移生成的文件。
参考资料
https://learn.microsoft.com/zh-cn/ef/core/get-started/overview/first-app?tabs=visual-studio
结尾
文章如有不妥之处,欢迎大家指正。