Related
I face the following error when adding the migration of database in .net core
This is the error:
This is the code in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
This is the ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
This is the ApplicationUser:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.
With that will be able to understand what is the problem. the verbose will display all steps of the execution.
In visual studio use:
add-migration Added_something -verbose
For the CLI use:
dotnet ef migrations add Added_something --verbose
This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.
My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.
this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.
at the end Build -> Clean Solution in your project and then try running your command again.
Help Link
add migration command cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
update database command cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
remove migration command cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
Entity Framework Core tools reference - .NET Core CLI
I also had same problem today when I was running the dotnet ef migrations add <MigrationName>
I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.
I was able to resolve it from CLI.
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
It must be something with dynamic DbContext object invocation with Reflection playing here.
This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)
Seems you are your inheritance is wrong.
public ApplicationDbContext : IdentityDbContext
should be
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
or
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
if you also extend roles class.
when you want to create an context with an extended user class (instead of IdentityUser)
Try This one as of March 2021 - VS 16.9.2
I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the #AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!
If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
I found I was missing:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
I had multiple startup projects (different API's).
I was at a different level in the PM console.
Then I learned I had to close SQL management so I can run PM console commands.
I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing.
Adding the "-startup-project" argument worked for me.
I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.
In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error
This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json
run your migration with the --verbose option to see all errors and warnings
dotnet ef migrations add YourMigrationName --verbose
If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.
It worked for me to create the migration in EFCore.
Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.
Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema. In most cases, it is desirable
that the DbContext thereby created is configured in a similar way to
how it would be configured at run time.
Here's how your DB context factory class might look like:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
I faced the same problem in .Net 6
Make sure that AddDBContext is above builder.Build
builder.Services.AddDbContext<DatabaseDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
In the Program.cs file, do not write anything with builder.Services.... below
var app = builder.Build()
line otherwise it throughs an error.
Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
I was getting the same error....except the code was working fine just minutes before.
I was in the process of replacing some property attributes with Fluent API
I had three projects: WebApp, DataAccess Library and Model Library.
After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp.
Every thing was working again...and I could not recreate the error.
This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
Fixing my appsettings.json file resolved the issue.
I had the same error, just modify the program class. Net Core 3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.
Getting the same error...
Here's how I got there: Created a new ASP.NET Core Web App
(Model-View-Controller) Target Framework was .NET Core 3.1
(LTS) Authentication Type: Individual Accounts
Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.
I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.
Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters
In my case I was using a custom IdentityErrorDescriber :
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
and in my MyIdentityErrorDescriber I was using resources to translate errors.
and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.
I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.
I faced the same error and when I added this it worked fine:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.
This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.
In my case, I built my project and it worked. So try to do this easy step before anything else.
For future reference, a simple gotcha, has got me before.
Make sure you actually have a value inside of the connection string in your appsettings.json file.
I.e.
This will throw an error:
"ConnectionStrings": {
"ConnectionString": ""
},
This will not:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.
I am trying to seperate my Data Acccess from my WebAPI.
So I made a simple .NET 6 class library (dotnet new classlib -f net6.0 ) for my entity framework core 6 models and context.
I ran dotnet user-secrets init in the WebAPI project and then copied the <UserSecretsId> from the .csproj file to the .csproj file of the DAL project.
// (school.WebAPI.csproj) added reference in School.WebAPI to School.DAL
<ProjectReference Include="..\School.DAL\School.DAL.csproj" />
Now I am trying to scaffold the database.
dotnet ef dbcontext scaffold name=ConnectionStrings:SchoolDev Microsoft.EntityFrameworkCore.SqlServer -o Models --context-dir Data --schema dbo -f
Which generates the following error:
System.InvalidOperationException: A named connection string was used, but the name 'ConnectionStrings:SchoolDev' was not found in the application's configuration.
When I run the same command in the WebAPI project it works perfectly.
I read something about var builder = WebApplication.CreateBuilder(args); being used by the CLI to read the secrets.json. But I got confused because I don't feel like WebApplication.CreateBuilder(args) belongs in a DAL project.
How do you set up access to user-secrets from cli in a class library?
You can run the EF command in the solution root with -s path/to/API_project -p path/to/SQL_project.
This way it uses the startup project (-s) to figure out configuration and the project (-p) to locate EF context.
Documentation: https://learn.microsoft.com/en-us/ef/core/cli/dotnet#target-project-and-startup-project
I face the following error when adding the migration of database in .net core
This is the error:
This is the code in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllers();
}
This is the ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<ApplicationUser> applicationUsers { get; set; }
}
This is the ApplicationUser:
public class ApplicationUser : IdentityUser
{
[Required]
[Column(TypeName = "nvarchar(150)")]
public string UserFName { get; set; }
[Required]
public string UserLName { get; set; }
}
I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.
With that will be able to understand what is the problem. the verbose will display all steps of the execution.
In visual studio use:
add-migration Added_something -verbose
For the CLI use:
dotnet ef migrations add Added_something --verbose
This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.
My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.
this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.
at the end Build -> Clean Solution in your project and then try running your command again.
Help Link
add migration command cli:
dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
update database command cli:
dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
remove migration command cli:
dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose
Entity Framework Core tools reference - .NET Core CLI
I also had same problem today when I was running the dotnet ef migrations add <MigrationName>
I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.
I was able to resolve it from CLI.
dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.
public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}
It must be something with dynamic DbContext object invocation with Reflection playing here.
This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)
Seems you are your inheritance is wrong.
public ApplicationDbContext : IdentityDbContext
should be
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
or
public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>
if you also extend roles class.
when you want to create an context with an extended user class (instead of IdentityUser)
Try This one as of March 2021 - VS 16.9.2
I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the #AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!
If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.
using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}") //connection string
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
I found I was missing:
Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design
I had multiple startup projects (different API's).
I was at a different level in the PM console.
Then I learned I had to close SQL management so I can run PM console commands.
I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing.
Adding the "-startup-project" argument worked for me.
I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.
In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error
This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json
run your migration with the --verbose option to see all errors and warnings
dotnet ef migrations add YourMigrationName --verbose
If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.
It worked for me to create the migration in EFCore.
Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.
Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema. In most cases, it is desirable
that the DbContext thereby created is configured in a similar way to
how it would be configured at run time.
Here's how your DB context factory class might look like:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
public BlazorContext CreateDbContext(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Filename=db.sqlite3");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
I faced the same problem in .Net 6
Make sure that AddDBContext is above builder.Build
builder.Services.AddDbContext<DatabaseDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();
In the Program.cs file, do not write anything with builder.Services.... below
var app = builder.Build()
line otherwise it throughs an error.
Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
});
}
For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring
I was getting the same error....except the code was working fine just minutes before.
I was in the process of replacing some property attributes with Fluent API
I had three projects: WebApp, DataAccess Library and Model Library.
After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp.
Every thing was working again...and I could not recreate the error.
This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.
Fixing my appsettings.json file resolved the issue.
I had the same error, just modify the program class. Net Core 3.0
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
To
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.
Getting the same error...
Here's how I got there: Created a new ASP.NET Core Web App
(Model-View-Controller) Target Framework was .NET Core 3.1
(LTS) Authentication Type: Individual Accounts
Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.
I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.
Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters
In my case I was using a custom IdentityErrorDescriber :
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
and in my MyIdentityErrorDescriber I was using resources to translate errors.
and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.
I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.
I faced the same error and when I added this it worked fine:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddScoped<IuserRepositorhy, UserRepository>();
I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.
This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.
In my case, I built my project and it worked. So try to do this easy step before anything else.
For future reference, a simple gotcha, has got me before.
Make sure you actually have a value inside of the connection string in your appsettings.json file.
I.e.
This will throw an error:
"ConnectionStrings": {
"ConnectionString": ""
},
This will not:
"ConnectionStrings": {
"ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
},
In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.
First I run the following setup
Xamarin Forms - Entity Framework Core 2.2 - SQLite - Android - DEBUG
And everything works fine. The .db file is generated properly and queries are executed on the database.
Then I prepared the application for production and I changed the DEBUG to RELEASE compiled, and packed into an apk. As installed on the device the application always crashes when calling either Database.Migrate() or Database.EnsureCreated()
The scenario is the same on every application I tried. App runs properly in emulator and on the device being in DEBUG mode. App crashes on every Android device when creating the database.
This is the instantiation of the DbContext
public ItemContext(DbContextOptions<ItemContext> options)
: base(options)
{
//Database.Migrate();
Database.EnsureCreated();
}
This is how the constructor is called
public void Load()
{
string databasePath = DependencyService.Get<ILocalFileStorageService>().GetDatabaseFilePath("ItemSQLite.db");
string connectionString = $"Filename={databasePath}";
DbContextOptions<ItemContext> options = new DbContextOptionsBuilder<ItemContext>()
.UseSqlite(connectionString)
.Options;
dataService = new DataService(new ItemContext(options));
}
This is how I retrieve the filepath on Android.
public string GetDatabaseFilePath(string fileName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(path, fileName);
}
When looking on the Android Device Monitor a very long error is displayed
The beginning is
somewhere later there is the EnsureCreated method listed
The Question: Why is this happening and how to make the application runnable on production?
Do you have linking enabled in your release build configuration? According to this https://github.com/aspnet/EntityFrameworkCore/issues/10963 the compiler requires hints to not link assemblies accessed through reflection internally in EF Core. You can try switching to "Link sdk assemblies only" to see if that fixes the issue. If it does then you will need to identify the assemblies and mark them to be preserved. There's some more info on that here: Xamarin iOS Linker Issue and here: https://learn.microsoft.com/en-us/xamarin/android/deploy-test/linker#linkskip.
I can't personally test at the moment but I think putting [assembly: Preserve (typeof (System.Linq.Queryable), AllMembers = true)] (or whatever assembly might be causing it) in your App.xaml.cs should do it.
I'm deploying a asp.net core 2.0 website to IIS 10.
I've made sure that my app is using the correct configuration for ISS in the program.settings file.
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
And in my startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<IISOptions>(options =>
{
});
services.AddMvc();
}
Yet when I run dotnet website.dll from the command line I get the below error message shown in the command line window:
An assembly specified in the application dependencies manifest
(website.deps.json) was not found:
package: 'Microsoft.AspNetCore.Antiforgery', version: '2.0.1'
path: 'lib/netstandard2.0/Microsoft.AspNetCore.Antiforgery.dll' This assembly was expected to be in the local runtime store as the
application was published using the following target manifest files:
aspnetcore-store-2.0.3.xml
Based off the error message, i'm guessing Microsoft.AspNetCore.Antiforgery isn't being bundled when I publish since I do not receive this error when debugging.
How can I ensure that my app can find Microsoft.AspNetCore.Antiforgery when published to a live environment?
EDIT: This is a basic .net core website. No changes have been made to the standard project at this time apart from the above changes for deployment with IIS.
When I run the project from IIS instead of the command line I get a 502.5 error message.
I was able to fix this issue by updating the .net core runtime on the server to v2.0.3.
This issue occurs if
You have an existing server running v2.0.0 of the .net core runtime.
You create an app targeting v2.0.3 of the SDK
You publish the v2.0.3 app to a server running v2.0.0
The issue can be resolved by installing v2.0.3 of the runtime on the server. You can download the runtime from the microsoft site here https://www.microsoft.com/net/download/windows
If you are actually using this library, make sure that your *.csproj file has the corresponding explicit reference:
<PackageReference Include="Microsoft.AspNetCore.Antiforgery" Version="..." />
Then, play with the PublishWithAspNetCoreTargetManifest property to resolve the aforementioned issue with a mismatched manifest.
Check out the following threads to learn more about possible issues while its deployment:
An assembly specified in the application dependencies manifest (RhWeb.deps.json) was not found
published application is missing assembly (missing runtime store associated ...) [2.0.0-preview2-005905]
HTTP Error 502.5 - Microsoft.AspNetCore.Antiforgery.dll
I had this issue - simple workaround, actually install the NuGet package (I wasn't using it).
Microsoft.AspNetCore.Antiforgery
Published, deployed - fixed the issue.
In another case, when I published the project, a lot of the dlls weren't being placed in the publish folder - including Antiforgery. The below appears to force publishing to add all the required dlls.
Edit your projectname.json file to ensure PropertyGroup contains PublishWithAspNetCoreTargetManifest = false:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>
Interested to know why the above works?!
This also problem happens if Antiforgery is called but Antiforgery is not installed.
Can be fixed by installing Microsoft.AspNetCore.Antiforgery by Nuget package manager.
I fixed this issue on my inhouse windowsserver with this solution
* go to netcore https://github.com/dotnet/core/tree/master/release-notes
* go to the lastest version of the core runtime 2.?
* download DotNetCore.2.0.6-WindowsHosting.exe in my case
https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.6-download.md#net-core-runtime-only-installation
Install this on server and the error was solved for me. Hope this helps anyone.
Got this error after updating Microsoft.AspNetCore.All from v2.0.7 to v2.0.8 (latest at the time) and then publishing to a server that was running .NET Core Runtime v2.0.7 (latest at the time).
Downgraded Microsoft.AspNetCore.All back down to v2.0.7, re-published, and everything works.
If you publish the app as a self-contained ASP.NET Core 2.2 apps as per the linked screenshot (I don't have enough rep for inline image), it will fix this issue.
Self contained:
This can be set when editing your publish settings.
If this issue is related to your Razor mail template, you can add "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation". When I add, the problem is solved.