Error when trying to share DB Context through and migrate - c#

I am starting to lean asp.net core 3 and I have an issue at present. I am trying to share my db context like I used to through a .net core dll but I have an error.
I have the following declared in my class.
// This method gets called by the runtime. Use this method to add services to e container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<DbContext_Model>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppliedContext")));
}
The db context which I have in my core dll project solution.
public class DbContext_Model: DbContext
{
public DbContext_Model(DbContextOptions<DbContext_Model> options)
: base(options)
{ }
public DbSet<Customer> Customer { get; set; }
public DbSet<Policys> Policys { get; set; }
}
I have declared my connection string below with password masked
"ConnectionStrings": {
"AppliedContext": "Server=DESKTOP\MSSQLSERVER2017;Database=Systems;User
Id=sa;Password=xxxxx;MultipleActiveResultSets=true"
But When I do Add-Migration InitalCreate I get this error.
Unable to create an object of type 'DbContext_Model'. For the
different patterns supported at design time, see
https://go.microsoft.com/fwlink/?linkid=851728
Is sharing of the context no longer allowed between .net core libarys and a web site ?
Edit 2
Please see screen shot which shows I am selecting the correct project.
Edit 3
That seemed to cause an another error the suggestion below. So I added the nugets in for the json tooling but still get this error.
dotnet ef migrations add InitialCreate System.MissingMethodException:
Method not found: 'System.Text.Json.JsonDocument
System.Text.Json.JsonDocument.Parse(System.IO.Stream,
System.Text.Json.JsonReaderOptions)'. at
Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute() at
Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.b__0()
at
Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[]
args) at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[]
args) Method not found: 'System.Text.Json.JsonDocument
System.Text.Json.JsonDocument.Parse(System.IO.Stream,
System.Text.Json.JsonReaderOptions)'. PM> dotnet ef migrations add
InitialCreate

Try something like this:
options.UseSqlServer(
Configuration.GetConnectionString("AppliedContext"),
options => options.MigrationsAssembly(<DB_PROJECT>)
Then you should be able to run this from within the folder that has the DbContext project:
dotnet ef migrations add <NAME> --startup-project <STARTUP_PROJECT>

From the screenshot in your Edit3, your need to update EF Core related package to version 3.0 . In Manage NutGet Packages , check Include prerelease next to the search box and update them to latest version like below :
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview8.19405.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-preview8.19405.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
Note :When adding migration , set your web application as the Startup project and set the class library as the default project where you want Migration folder generates.
Reference :https://dotnetthoughts.net/using-ef-core-in-a-separate-class-library/

The screenshot of your Edit3 seems to indicate that your EF tool version is outdated. You can check by executing:
dotnet ef --version
on the command line. If it's not preview8, then install it:
dotnet tool update dotnet-ef --version 3.0.0-preview8.19405.11
(optionally use the --global switch).
Beware: EF preview8 has an additional issue when used with HasData. It should be fixed in preview9 (which at the time of this writing is not out yet).

Related

Checking if a record exist returns "Sequence contains more than one matching element." for Net5 with Entity Framework 5

I have an .Net5 solution using Entity Framework 5.0.0. Im able to save data to the Backend SQL DB and all is well. But when I try to check is a record exist using the statement below im getting an error "Sequence contains more than one matching element."
var status = await dbContext.Item.AnyAsync(x => x.Name == "Bread")
I’m not sure what’s causing this. Any help appreciated
Im using the following packages
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0">
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0">
This is not an error that should come back from AnyAsync. I suspect there is something in the structure of your items (e.g. via a foreign key) that is generating the error. Use ToTraceString() to find out the underlying SQL query.
I solved it by updating all my EntityFramework related packages to
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.17">
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.17">

Why is Entity Framework generating an invalid DbContext class in my .NET Core class library?

I'm trying to get Entity Framework Core setup inside an empty .NET 5 library.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.3.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>
I've run the EF scaffolding tool (5.0.3) to generate my models and the DbContext with this command:
dotnet ef dbcontext scaffold 'server=localhost;database=techtest;user=root' MySql.EntityFrameworkCore -o Model -c DbContext
It successfully connects to the MySql database and generates the models; however, the DbContext that is created has several errors and I'm not sure what's causing them. I haven't altered the code at all.
DbContext.cs(26,26): Error CS0146: Circular base type dependency involving 'DbContext' and 'DbContext' (CS0146) (TechTest.Common)
DbContext.cs(33,33): Error CS0115: 'DbContext.OnConfiguring(DbContextOptionsBuilder)': no suitable method found to override (CS0115) (TechTest.Common)
DbContext.cs(33,33): Error CS0115: 'DbContext.OnModelCreating(ModelBuilder)': no suitable method found to override (CS0115) (TechTest.Common)
DbContext.cs(54,54): Error CS0311: The type 'TechTest.Common.Model.DbContext' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptions<TContext>'. There is no implicit reference conversion from 'TechTest.Common.Model.DbContext' to 'Microsoft.EntityFrameworkCore.DbContext'. (CS0311) (TechTest.Common)
Tried using different versions of the tools and packages, including Pomelo but it doesn't change anything.
What is actually happening here?
Don't call your class DbContext. You can't have a class with the same name as the base class. A better name would be TechTestDbContext:
dotnet ef dbcontext scaffold 'server=localhost;database=techtest;user=root' MySql.EntityFrameworkCore -o Model -c TechTestDbContext

I get an error when I add migration using Entity Framework Core

I built a console project and use code first to map model to database. When I run the command of Add-Migration InitialMigration, I get an error:
Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitorFactory' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.
The DbContext is:
class ActorDbContext : DbContext
{
public DbSet<Actor> Actors { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
#"Server=(localdb)\mssqllocaldb;Database=ActorDb;"
+ "Trusted_Connection=True;");
}
}
The entity is:
public class Actor
{
public int Id { get; set; }
public String Name { get; set; }
public int Age { get; set; }
public bool AcademyWinner { get; set; }
}
I just ran into this same issue using VS for Mac.
My problem was I had the following versions of packages installed:
Microsoft.EntityFrameworkCore.Tools 5.0.0-preview.8.20407.4
Microsoft.EntityFrameworkCore.Design 5.0.0-preview.8.20407.4
Microsoft.EntityFrameworkCore.SqlServer 3.1.8
Take note of the different versions used.
To correct the issue I uninstalled the preview versions of the packages and installed the latest stable versions.
Microsoft.EntityFrameworkCore.Tools 3.1.8
Microsoft.EntityFrameworkCore.Design 3.1.8
Microsoft.EntityFrameworkCore.SqlServer 3.1.8
Again take note of the versions for all 3 packages.
Once I had installed the correct version of each package the issue was resolved and my Add-Migration worked.
You must include all the following packages to be of same version:
Microsoft.EntityFrameworkCore
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
I tried it and it run well.
I am adding to the answer of [mohammed-abdelwahab][1]
Below packages need to be of latest update:
Microsoft.EntityFrameworkCore
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
For that right-click on the project --> Manage Nuget Packages --> Click on updates and just update all one by one or add if not exists as below
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
PM> Install-Package Microsoft.EntityFrameworkCore.Tools
PM> Add-Migration InitialMigration
Good Luck :)
Maybe you're trying to mix different versions. Make sure that all versions are aligned.
Try changing your SqlServer to the latest version(5.0.0), I was running to exactly this same error, once I updated to the latest version it worked well.
I ran into the same problem when doing an old tutorial. The problem was I installed a package with the "-pre" clause.
Use the below commands:
Enlist installed packages in your project-
PM> Get-Package -ProjectName <YourProjectName>
Output:
Id Versions ProjectName
-- -------- -----------
Microsoft.EntityFrameworkCore.Tools {5.0.0-rc.2.20475.6} FirstEFCoreProject
Microsoft.EntityFrameworkCore.Sq... {3.1.9} FirstEFCoreProject
Uninstall the unstable package -
PM> Uninstall-Package Microsoft.EntityFrameworkCore.Tools
Reinstall the package (without the -pre) -
PM> Install-Package Microsoft.EntityFrameworkCore.Tools
And then add your migration again -
PM> Add-Migration InitialMigration
I also just had this issue. It turns out that I accidentally had both Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Sqlite installed.
I really just needed Sqlite, so I deleted the reference to SqlServer. I then had to fix a couple of places that referenced SqlServer, instead of Sqlite, I'd missed and now the error is gone.
Fixed after running in NuGet these 2 lines
Add-Migration Initial
and then
Update-Database
.NET Core 6.0.8
Version of Microsoft.EntityFrameworkCore should be Same for all Packages
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
Error comes with this
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0-preview.7.22376.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

Identity asp.net core 3.0 - IdentityDbContext not found

My app broke with the 3.0 release of .NET core with reference errors for IdentityDbContext. I'm looking through documentation for Identity on core 3.0 but it implies that IdentityDbContext should be there. It's the only error I'm getting with a couple DbContext errors.
I have a pretty simple API, no MVC views, just a data server that gives back JSON objects. It's based on Identity so it has the users and roles and claims. And it's starting to take advantage of that. My main DbContext extends IdentityDbContext<ApplicationUser> but after switching target platform to 3.0 after the upgrade, it says it doesn't exist and gives me compile errors. Has anyone run into this? Am I missing something? The migration and breaking changes pages don't seem to have anything addressing my issue.
DbContext looks like this:
using System;
using Microsoft.AspNetCore.Identity;
//using Microsoft.AspNetCore.Identity.EntityFrameworkCore; <- this no longer works either
using Microsoft.EntityFrameworkCore; //<- this I had to download as a package
using App.Constants;
using App.Models.Identity;
namespace App.Models
{
public class AppContext : IdentityDbContext<ApplicationUser> //<- error is right here
{
... my models
}
}
In ASP.NET Core 3.0, Entity Framework Core and Identity related packages have been removed from the Microsoft.AspNetCore.App metapackage. So you have to add those packages separately.
Add the following PackageReferences to your project's .csproj file as follows:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" />
</ItemGroup>
Now it will work!
For more details: Assemblies removed from the ASP.NET Core shared framework
if you have an error like "error CS0246: The type or namespace name 'IdentityDbContext' could not be found"
you can install bellow package for asp.net web api 3 project
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 5.0.0-preview.3.20215.14
in dotnet cli.its work for me.
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore -Version 5.0.0-preview.3.20215.14
this for package manager

How to create a new dotnet core application that has both auth and EF?

I can create a new dotnetcore app that has authentication/identity using the command line:
dotnet new mvc --auth Individual
How can i include entity framework in the project also?
TL;DR
You already have it in your project
Long form answer
After creating your application, it should have Entity Framework as a dependency. I'm assuming that you're running the .NET Core 2.0 SDK.
Here's the output from my machine
$ dotnet new mvc --auth Individual --name testForStackOverflow
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.
Processing post-creation actions...
Running 'dotnet restore' on testForStackOverflow/testForStackOverflow.csproj...
Restoring packages for testForStackOverflow/testForStackOverflow.csproj...
Restore completed in 40.17 ms for testForStackOverflow/testForStackOverflow.csproj.
Restore completed in 40.17 ms for testForStackOverflow/testForStackOverflow.csproj.
Restore completed in 25.25 ms for testForStackOverflow/testForStackOverflow.csproj.
Generating MSBuild file testForStackOverflow/obj/testForStackOverflow.csproj.nuget.g.props.
Generating MSBuild file testForStackOverflow/obj/testForStackOverflow.csproj.nuget.g.targets.
Restore completed in 2.84 sec for testForStackOverflow/testForStackOverflow.csproj.
Restore succeeded.
I then look a look at the csproj which was generated:
$ cd testForStackOverflow/
~/testForStackOverflow$ ls
app.db Data Startup.cs
appsettings.Development.json Extensions testForStackOverflow.csproj
appsettings.json Models Views
bower.json obj wwwroot
bundleconfig.json Program.cs
Controllers Services
~/testForStackOverflow$ cat testForStackOverflow.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<UserSecretsId>aspnet-testForStackOverflow-AD382505-1A70-4A75-8059-1E0E3897A088</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<None Update="app.db" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
The important line of the csproj is here:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
This is a reference to the ASP.NET Core metapackage. This package contains all of the common ASP.NET Core NuGet packages, including Entity Framework Core - as per this screen shot from NuGet (captured a few moments ago)
This means that part of the package restore operation included restoring EF Core into your project.
I would say that you should take a look at this documentation for EF Core - the link should take you directly to the section labelled "The Model". You don't need the stuff in the preceding section (labelled "Get Entity Framework Core") as you already have it.
Of course, if you're using version 1.x of the .NET Core SDK, then it's a slightly different story.

Categories

Resources