.Net Core-类库中创建CodeFirst

本文仅用来学习记录。
搭建项目架构的时候,需要在类库中进行CodeFirst数据迁移
 
1.在项目的解决方案中,添加类库ERPFrame.Model

2.在类库项目中 添加实体模型和数据上下文

其中 TopBaseModel是基类,用于生成唯一标识Guid
 1 public class TopBaseModel
 2     {
 3         private Guid _id;
 4         public Guid ID {
 5             get {
 6                 if (_id == Guid.Empty) {
 7                     _id = Guid.NewGuid();
 8                 }
 9                 return _id;
10             }
11             set {
12                 _id = value;
13             }
14         }
15     }
View Code
BaseModel继承TopBaseModel,生成创建人,创建日期,修改人,修改日期
 1 using System.ComponentModel.DataAnnotations;
 2 public class BaseModel:TopBaseModel
 3     {
 4         [Display(Name ="创建时间")]
 5         public DateTime? CreateTime { get; set; }
 6         [Display(Name ="创建人")]
 7         [StringLength(50, ErrorMessage = "{0}最多输入{1}个字符")]
 8         public string CreateBy { get; set; }
 9         [Display(Name = "修改时间")]
10         public DateTime? UpdateTime { get; set; }
11         [Display(Name = "修改人")]
12         [StringLength(50, ErrorMessage = "{0}最多输入{1}个字符")]
13         public string UpdateBy { get; set; }
14     }

Frame_User实体模型,继承BaseModel

 1 using System.ComponentModel.DataAnnotations;
 2 public class Frame_User:BaseModel
 3     {
 4         [Display(Name ="用户")]
 5         [StringLength(50, ErrorMessage = "{0}最多输入{1}个字符")]
 6         public string UserName { get; set; }
 7         [Display(Name = "角色名")]
 8         [StringLength(50, ErrorMessage = "{0}最多输入{1}个字符")]
 9         public string RoleName { get; set; }
10     }

ERPFrameDBContext数据上下文

1 public class ERPFrameDBContext : DbContext
2     {
3         public ERPFrameDBContext(DbContextOptions<ERPFrameDBContext> options) :  base(options)
4         {
5         }
6     
7         public DbSet<Frame_User> Frame_User { get; set; }
8     }

3. 项目文件配置

(1)“appsettings.json”添加配置项,数据库连接字符串

1 "ConnectionStrings": {
2     "todoContext": "Server=.;DataBase=ERPFrame;uid=sa;pwd=123456"
3   },

(2)“Startup.cs”依赖注入 读取上一步配置的数据库字符串信息,这里的 ERPFrameDBContext即上面的 数据上下文
  services.AddDbContext<ERPFrameDBContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("todoContext")));

如上所有配置完成后,重新编译成功后,在控制台进行数据库迁移 :

(1)执行“Add-Migration 版本信息”,如下图
 
(2)执行成功后,在类库项目中会显示对应的数据库迁移记录和快照
扫描二维码关注公众号,回复: 6947648 查看本文章
(3)执行“update-database”,同步表结构,在数据库便能看到对应的表
 
注:
可能会遇到的问题:
  Both Entity Framework 6.x and Entity Framework Core commands are installed. The Entity Framework 6 version is executing. You can fully qualify the command to select which one to execute, 'EntityFramework\Update-Database' for EF6.x and 'EntityFrameworkCore\Update-Database' for EF Core.
解决方法:
EntityFrameworkCore\Add-Migration InitialDb
EntityFrameworkCore\Update-Database

猜你喜欢

转载自www.cnblogs.com/ywkcode/p/11298752.html
今日推荐