how to setup EFcore database first in separate class library in ASP.NET Core MVC application?

asp.net-core entity-framework-core

Question

I have a DB and I want to add a separate class library for entity framework to access my data but when I run scaffold command it makes a DB model in my web application.

1
0
11/17/2018 5:05:55 PM

Accepted Answer

You should select your Data project as default project in package manager console.

enter image description here

Be careful, you have ef core references in data.csproj

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

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <RuntimeFrameworkVersion>2.0.5</RuntimeFrameworkVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0-preview3-35497" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0-preview3-35497" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.0-preview3-35497" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0-preview3-35497"/>
    <PackageReference Include="System.Data.Common" Version="4.2.1" />
  </ItemGroup>

</Project>

I realized that there are some errors in ClassLibrary projects. You can take a look at them:

https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet#targeting-class-library-projects-is-not-supported

https://github.com/dotnet/cli/issues/8735

https://github.com/aspnet/EntityFrameworkCore/issues/10298

0
11/13/2018 7:45:45 AM

Popular Answer

@ibrahimozgon's answer is right and helped me. However, I encountered a few errors in the DbContext class on the way which he didn't mention how to solve:

'EntityTypeBuilder' does not contain a definition for 'ToTable' and no accessible extension method 'ToTable' accepting a first argument of type 'EntityTypeBuilder' could be found (are you missing a using directive or an assembly reference?

and

'KeyBuilder' does not contain a definition for 'ForSqlServerIsClustered' and no accessible extension method 'ForSqlServerIsClustered' accepting a first argument of type 'KeyBuilder' could be found (are you missing a using directive or an assembly reference?

To resolve these errors in DbContext class, open up package manager console again and select the default project to be the class library. Enter these commands one by one:

- Install package:  Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.4  (or whichever latest version)
- Install package:  Install-Package Microsoft.EntityFrameworkCore.Relational -Version 2.2.4  (or whichever latest version)
- If errors persist try: Install-Package or Update-Package  Microsoft.EntityFrameworkCore.Tools  (or whichever latest version)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow