当前位置: 移动技术网 > IT编程>开发语言>.net > 在.NET Core类库中使用EF Core迁移数据库到SQL Server的方法

在.NET Core类库中使用EF Core迁移数据库到SQL Server的方法

2018年01月26日  | 移动技术网IT编程  | 我要评论
前言 如果大家刚使用entityframework core作为orm框架的话,想必都会遇到数据库迁移的一些问题。 起初我是在asp.net core的web项目中进行

前言

如果大家刚使用entityframework core作为orm框架的话,想必都会遇到数据库迁移的一些问题。

起初我是在asp.net core的web项目中进行的,但后来发现放在此处并不是很合理,一些关于数据库的迁移,比如新增表,字段,修改字段类型等等,不应该和最上层的web项目所关联,数据的迁移文件放到这里也感觉有点多余,有点乱乱的感觉,所以才想着单独出来由专门的项目进行管理会比较好,也比较清晰!

注意目标框架选择的是.net core 2.0而不是.net standard 2.0

0、前期准备

a)、表实体定义,这个是在.net standard 2.0的类库中存放的。

/// <summary>
 /// 系统应用的用户实体
 /// </summary>
 public class applicationuser : basemodel
 {
  /// <summary>
  /// 用户名
  /// </summary>
  public string username { get; set; }
  /// <summary>
  /// 密码
  /// </summary>
  public string password { get; set; }
  /// <summary>
  /// 邮件地址
  /// </summary>
  public string email { get; set; }
 }

b)、新建一个.net core 2.0的类库,并定义好我们所要使用的数据库上下文,很简单,接下来开始我们的正文

/// <summary>
 /// 系统上下文
 /// </summary>
 public class lightcontext : dbcontext
 {
  public lightcontext(dbcontextoptions<lightcontext> options) : base(options)
  {
  }
  /// <summary>
  /// 系统应用用户
  /// </summary>
  public dbset<applicationuser> applicationuser { get; set; }
  /// <summary>
  /// 角色表
  /// </summary>
  public dbset<role> role { get; set; }
 }

1、问题汇总

首先要确保仓储类库中已经引入以下两个nuget包,没有的话请使用包管理器进行安装。不建议直接引入原包:microsoft.aspnetcore.all,按需引入即可

install-package microsoft.entityframeworkcore.sqlserver
install-package microsoft.entityframeworkcore.tools

a)打开cmd,然后切换到类库所在路径下,执行以下命令。不过你也可以使用程序包管理器控制台(pmc)进行迁移,但是会有少许变化,部分命令见下表:

迁移命令描述 cmd命令 pmc命令
创建迁移:migrationname为迁移名称 dotnet ef migrations add migrationname add-migration migrationname
移除迁移(删除最近的一次迁移) dotnet ef migrations remove remove-migration
应用最新的迁移(使迁移文件应用到数据库) dotnet ef database update update-database
应用指定的迁移 dotnet ef database update migrationname update-database migrationname
查看迁移列表 dotnet ef migrations list
查看数据库上下文信息 dotnet ef dbcontext info

dotnet ef

错误提示:

未找到与命令“dotnet-ef”匹配的可执行文件

解决方法:

在项目文件light.repository.csproj中添加以下节点

<itemgroup>
 <dotnetclitoolreference include="microsoft.entityframeworkcore.tools.dotnet" version="2.0.1" />
</itemgroup>

重新执行上面的命令,如果出现了ef core的标志(一头蓄势待发的野马)表示已经成功

b)、执行以下命令进行迁移

dotnet ef migrations add initlightdb

错误提示:

the specified framework version '2.0' could not be parsed
the specified framework 'microsoft.netcore.app', version '2.0' was not found.
- check application dependencies and target a framework version installed at:
\
- alternatively, install the framework version '2.0'.

解决方法:

在项目文件中添加以下节点:

<propertygroup>
 <targetframework>netcoreapp2.0</targetframework>
 <runtimeframeworkversion>2.0.3</runtimeframeworkversion>
 </propertygroup>

c)、重新执行b步骤的命令,报错信息如下:

错误提示:

unable to create an object of type 'lightcontext'. add an implementation of 'idesigntimedbcontextfactory<lightcontext>' to the project, or see for additional patterns supported at design time.

这个问题如果是在web项目,并且配置了dbcontext的链接字符串的话,是不会出现此问题的。很显然是迁移命令没有找到dbconnectionstring导致的,接下来我们按照提示,实现一个idesigntimedbcontextfactory<lightcontext>试试

解决方法:

创建一个与dbcontext同一目录下的designtimedbcontextfactory文件,然后实现接口中的方法createdbcontext,并配置connectionstring

public class designtimedbcontextfactory : idesigntimedbcontextfactory<lightcontext>
 {
  public lightcontext createdbcontext(string[] args)
  {
   var builder = new dbcontextoptionsbuilder<lightcontext>();
   builder.usesqlserver("server=(localdb)\\mssqllocaldb;integrated security=true;initial catalog=light;");
   return new lightcontext(builder.options);
  }
 }

再次执行迁移命令,终于成功了。

成功提示:

done. to undo this action, use 'ef migrations remove'

同时类库下面会生成migrations文件夹以及相关的迁移文件

2、小试迁移命令

a)、使用以下命令应用迁移,生成数据库和表

dotnet ef database update

通过vs的sql server资源管理器查看生成数据库的结构,其中__efmigrationshistory为每次迁移的记录表

b)、因为string类型的字段迁移到数据库之后的数据类型为nvarchar(max)并且是可空类型的,下面我们就使用fluent api对applicationuser表字段进行配置,同样你也可以使用属性注解的方式进行配置,因为我自己不喜欢“污染”表实体

public static void configapplicationuser(modelbuilder modelbuilder)
  {
   modelbuilder.entity<applicationuser>(m =>
   {
    m.property(t => t.email)
      .hasmaxlength(50);
    m.property(t => t.username)
      .isrequired()
      .hasmaxlength(50);
    m.property(t => t.password)
      .isrequired()
      .hasmaxlength(20);
   });
  }

然后同样使用上面的两条命令重新迁移并更新数据库结构

观察数据库表结构已经更新

同理添加字段,删除字段都是一样的迁移操作,还是很方便的

3、扩展

a)、为了方便演示,其实上面在类库中执行迁移时的数据库连接字符串是写死的,那么最好的办法是应该去读取web项目下已经配置好的连接,这样就能保证上下的一致性,不用再去为了ef的迁移而单独维护一个多余的数据库连接配置。改造也很简单,即通过configuration组件读取appsettings.json的connectionstrings节点,改造之后是这样子的:

public class designtimedbcontextfactory : idesigntimedbcontextfactory<lightcontext>
 {
  public lightcontext createdbcontext(string[] args)
  {
   directory.setcurrentdirectory("..");//设置当前路径为当前解决方案的路径
   string appsettingbasepath = directory.getcurrentdirectory() + "/light.authorityapi";//改成你的appsettings.json所在的项目名称
   var configbuilder = new configurationbuilder()
    .setbasepath(appsettingbasepath)
    .addjsonfile("appsettings.json")
    .build();
   var builder = new dbcontextoptionsbuilder<lightcontext>();
   //builder.usesqlserver("server=(localdb)\\mssqllocaldb;integrated security=true;initial catalog=light;");
   builder.usesqlserver(configbuilder.getconnectionstring("lightconnection"));
   return new lightcontext(builder.options);
  }
 }

注意需要额外引入下面这个nuget包:

install-package microsoft.extensions.configuration.json

b)、属性注解[column(order = 1)]对ef core来说还没有达到可以调整数据库生成字段的顺序,不过我们还是可以修改迁移文件的实体属性的顺序来达到我们想要的效果。下面是我调整之后重新生成的表,是不是看出来和上面的有什么不同,一图胜万语:

c)、最后一步,自己动手试试看:创建一个seeddata迁移文件来添加数据库的初始数据。:)

4、最后

ef core的强大远不止这些,还有更多的使用方法等着我们去发现,去探索。每天进步一点点,是件很愉快的事情!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网