Entity Framework Core Migration for ASP.Net Core Class Library

三世轮回 提交于 2019-12-04 09:24:39

UPDATE: And now this answer appears to be out of date! Turns out 1.1 has removed this feature. After upgrade to 1.1 it no longer works. Odd that this would stop working. Setting up the class library to work like a console application as Ben Cull suggests appears to be the way to handle it when using EF Core 1.1


That blog article is pretty old. Most things that are from before the .Net Core release while still usually useful, need to be taken with a grain of salt.

You no longer have to fake out a console app in the class library. I whipped together a sample identity application where the User and DbContext were in a class library.

The class library project.json looked like this:

{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Microsoft.EntityFrameworkCore": "1.0.1",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview4-final"
  },
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview4-final"
  },
  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}

To show the ClassLibrary namespace and the identity schema coming through in the migration.

A few subtle things to note:

  • Passed the options in the DbContext constructor to the base constructor
  • WebApplication was the startup project. The default project in the Package Manager Console was the Class Library. This is so that it knows where to find Startup.

The whole example solution I put together has been put up on Github if you want to use it as a baseline.

for core 1.1 after adding the packages with nuget it will not work directly, you will need also to edit the .csproj file like that

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
  </ItemGroup>

</Project>

reference: https://www.benday.com/2017/02/14/walkthrough-entity-framework-core-1-1-with-migrations/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!