EF Core 2.1 project Add-Migration NullReferenceException - asp.net

I am getting a NullReferenceException on a project recently converted to dotnet core 2.1.
My EF library project is dotnet core 2.1. Code first migrations.
CsvHelper 6.0.2
Microsoft.EntityFrameworkCore 2.1.0
Microsoft.EntityFrameworkCore.Design 2.1.0
Microsoft.EntityFrameworkCore.SqlServer 2.1.0
Microsoft.EntityFrameworkCore.Tools 2.1.0
Output from the add-migration command
PM> add-migration -Name MyMigration -Context EscData01Context -Project Data\EscData01 -StartupProject PacmsTri -verbose
Using project 'Data\EscData01'.
Using startup project 'PacmsTri'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\temp\PacmsTri\dev\***\source\PacmsTri\bin\Debug\netcoreapp2.1\PacmsTri.deps.json --additionalprobingpath "C:\Users\***\.nuget\packages" --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\temp\PacmsTri\dev\***\source\PacmsTri\bin\Debug\netcoreapp2.1\PacmsTri.runtimeconfig.json "C:\Users\***\.nuget\packages\microsoft.entityframeworkcore.tools\2.1.0\tools\netcoreapp2.0\any\ef.dll" migrations add MyMigration --json --context EscData01Context --verbose --no-color --prefix-output --assembly C:\temp\PacmsTri\dev\****\source\PacmsTri\bin\Debug\netcoreapp2.1\EscData01.dll --startup-assembly C:\temp\PacmsTri\dev\****\source\PacmsTri\bin\Debug\netcoreapp2.1\PacmsTri.dll --project-dir C:\temp\PacmsTri\dev\****\source\Data\EscData01\ --language C# --working-dir C:\temp\PacmsTri\dev\****\source --root-namespace Sms.Office.Data.EscData01
Using assembly 'EscData01'.
Using startup assembly 'PacmsTri'.
Using application base 'C:\temp\PacmsTri\dev\***\source\PacmsTri\bin\Debug\netcoreapp2.1'.
Using working directory 'C:\temp\PacmsTri\dev\***\source\PacmsTri'.
Using root namespace 'Sms.Office.Data.EscData01'.
Using project directory 'C:\temp\PacmsTri\dev\***\source\Data\EscData01\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding IWebHost accessor...
Using environment 'Development'.
Using application service provider from IWebHost accessor on 'Program'.
Found DbContext 'AuthDbContext'.
Found DbContext 'DmsContext'.
Found DbContext 'EscData01Context'.
Found DbContext 'MailServicesContext'.
Found DbContext 'PmsDdContext'.
Finding DbContext classes in the project...
Using context 'EscData01Context'.
Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.1.0-rtm-30799 initialized 'EscData01Context' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
Finding design-time services for provider 'Microsoft.EntityFrameworkCore.SqlServer'...
Using design-time services from provider 'Microsoft.EntityFrameworkCore.SqlServer'.
Finding design-time services referenced by assembly 'PacmsTri'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'PacmsTri'...
No design-time services were found.
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.EntityFrameworkCore.Metadata.Internal.TableMapping.<>c.<GetRootType>b__10_0(IEntityType t)
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.EntityFrameworkCore.Metadata.Internal.TableMapping.GetRootType()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetSortedProperties(TableMapping target)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Add(TableMapping target, DiffContext diffContext)+MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.DiffCollection[T](IEnumerable`1 sources, IEnumerable`1 targets, DiffContext diffContext, Func`4 diff, Func`3 add, Func`3 remove, Func`4[] predicates)+MoveNext()
at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IModel source, IModel target)
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.
PM>
I have tried adding a IDesignTimeServices object to my startup project, and tried adding a IDesignTimeDbContextFactory as well.
I also tried creating a new sample project with the same dotnet and EF versions numbers, pointing at same db and was able to generate the context and create the migration successfully. So there must be some difference between the two project I cannot see.
PM> add-migration MyMigration2 -Project ClassLibrary1 -StartupProject WebApplication20 -Context ESC_DATA01Context
Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.1.0-rtm-30799 initialized 'ESC_DATA01Context' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
To undo this action, use Remove-Migration.
Any help greatly appreciated.
Update:
I had originally posted that this error was caused by migration of the project to standard 2.0 but discounted that idea after converting it back to dotnetcore2.1 and error persisted.

Looks like this error was caused by some references to models in my ModelSnapshot class that did not exist anymore. Including some Identity models that were left behind after I removed AspNetCore.Identity from the Context.
Deleting the code below from my EscData01ContextModelSnapshot fixed the issue.
modelBuilder.Entity("Sms.Office.Data.EscData01.Models.ExcelTemplate", b =>
{
b.HasOne("Sms.Office.Data.EscData01.Models.File", "File")
.WithMany()
.HasForeignKey("FileId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Sms.Office.Data.EscData01.Authentication.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Sms.Office.Data.EscData01.Authentication.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Sms.Office.Data.EscData01.Authentication.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Sms.Office.Data.EscData01.Authentication.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Sms.Office.Data.EscData01.Authentication.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Sms.Office.Data.EscData01.Authentication.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});

Related

How to use Dnlib to Import a runtime types and method from a specific dotnet framework like 4.8

My project is using .NET core "7.0" and the targeted module is "4.8" and when I try to import "GetString" method and inject it to the module using Dnlib, it references the higher version "7.0" instead of "4.8" and the output exe will crash because it can't find that higher reference dll.
....
....
body.Instructions.Add(new Instruction(OpCodes.Call, module.Import(typeof(Encoding).GetMethod("get_UTF8", new Type[] { }))));
.....
.....
body.Instructions.Add(new Instruction(OpCodes.Callvirt, module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]), typeof(Int32), typeof(Int32) }))));
Higher version
Any Idea how to import the right version.

EF Core scaffold DbContext for old Oracle database

I have an old Oracle Database (11.2.0.4.0) that I would like to scaffold using EF Core 6.4.4 and Oracle.EntityFrameworkCore 6.21.61.
The scaffolding command I use is:
Scaffold-DbContext "User Id=User;Password=Pass;Data Source=Inst;" Oracle.EntityFrameworkCore -OutputDir Models -Context MyTestContext -ContextDir . -force -Tables Table1, Table2 ...
It does a great job about the entities themself, but it does not recognize the relations between tables.
When scaffolding is done, I can set compatibility through UseOracleSQLCompatibility, but I am not aware of a way to tell scaffolding about compatibility.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.LogTo(message => Debug.WriteLine(message));
optionsBuilder.UseOracle("User Id=User;Password=Pass;Data Source=Inst;",
b => b.UseOracleSQLCompatibility("11"));
}
}
When doing a
var master = db.MasterEntities.Where(m => m.MasterId == 1)
.Include(m => m.Details).ToList();
it returns a list with one master, all properties correctly filled, but with no details.
The SQL debug info sent to the debug window only is about querying the master table.
The problem here was not the scaffolding.
The problem was .Include
There was a
using System.Data.Entity;
where there needed to be a
using Microsoft.EntityFrameworkCore;

View throws "The type or namespace name 'Microsoft' could not be found in the global namespace" with Kestrel running from .NET 4.6.1 Service

I'm about to integrate the ASP.NET Core Webserver into a .NET 4.6.1 project by adding the NuGet packages Microsoft.AspNetCore.* and running the following code at service start:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
static Action<IServiceCollection> _configureServices = (services) => {
services.AddMvc();
services.AddRouting();
};
static Action<IApplicationBuilder> _configure = app => {
app.UseDeveloperExceptionPage();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "app",
template: "app",
defaults: new { controller = "Home", action = "App" });
});
app.Run((ctx) => ctx.Response.WriteAsync("Page not found."));
};
protected void StartKestrel()
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://localhost:5000/;https://localhost:5001")
.ConfigureServices(_configureServices)
.Configure(_configure)
.Build();
host.Run();
}
I've managed to run everything fine, the routes and controllers are working perfectly. I'm just not able to return Views from Controllers, it always brings up the error page where it cannot locate the .NET Dlls (See below.)
Am I missing something? Do I need to add a web.config somewhere or missing a build step?
An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately.
Generated Code
>One or more compilation references may be missing. If you're seeing this in a published application, set 'CopyRefAssembliesToPublishDirectory' to true in your project file to ensure files in the refs directory are published.
>
>> The type or namespace name 'Microsoft' could not be found in the global namespace (are you missing an assembly reference?)
>>>[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore._Views_Home_Index), #"mvc.1.0.view", #"/Views/Home/Index.cshtml")]
>>
>> The type or namespace name 'Microsoft' could not be found in the global namespace (are you missing an assembly reference?)
>>>[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(#"/Views/Home/Index.cshtml", typeof(AspNetCore._Views_Home_Index))]
>>
>>Predefined type 'System.Type' is not defined or imported
>>>[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore._Views_Home_Index), #"mvc.1.0.view", #"/Views/Home/Index.cshtml")]
>>[...]

A named connection string was used, but the name 'tumoDB' was not found in the application's configuration. .Net core 3.0 REST API

Hi Could you please assist,i have run a scafold from my database using the below PM command and it works fine and the DB context is created.
Scaffold-DbContext "Data Source=(localhost);Initial Catalog=tumoDB;User ID=tumo;password=****" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Infrastructure\Models -Tables BnplIndicator -f
But when i try to follow .Net security principles by placing th the connectionstring in appsettings.json,i get the error in the title that the name of my DB(tumoDB) is not found,please see my connection strings bellow.
"ConnectionStrings": {
"MySql": {
"PhoneAppDB": {
"ConnString": "Server=(localhost)\Sql1;uid=tumo;pwd=****;Convert Zero Datetime=True;",
// "ConnString": "Server=(localhost)\Sql2;port=3030;Database=MohemStores;user=root;password=***;",
"Timeout": 60000,
"MaxRetries": 6
}
},
"SqlServer": {
"tumoDB": {
"ConnString": "Data Source=(localhost);Initial Catalog=tumoDB;User ID=tumo;Password=***;",
"Timeout": 60000,
"MaxRetries": 5
}
}
},
...
and now i use this below i get the error:tumoDB was not found in application configuration
Scaffold-DbContext -Connection Name=tumoDB Microsoft.EntityFrameworkCore.SqlServer -OutputDir Infrastructure\Models -Tables BnplIndicator -force
I researched and even added the code in the Iconfiguration in Startup.cs as recommended but still getting the same error,please note all required packages (EF.Sqlserver and EF.tools) are installed properly and the API runs it is just the command to scafold DBcontext using the name that gives problems.
services.AddCustomDataStoreConfiguration(Configuration);
services.AddDbContext<tumoDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("tumoDB")));
I actually found what the answer was,you cannot create a sub connection string under another connection string.
Solution:
"ConnectionStrings": {
"PhoneAppDB":"Server=(localhost)\Sql1;uid=tumo;pwd=****;Convert Zero Datetime=True;",
"tumoDB":
"ConnString": "Data Source=(localhost);Initial Catalog=tumoDB;User ID=tumo;Password=***;"
},

ILoggingBuilder does not have AddEventSourceLogger with 0 parameters. How to initialize this logging

'ILoggingBuilder' does not contain a definition for 'AddEventSourceLogger' and no accessible extension method 'AddEventSourceLogger' accepting a first argument of type 'ILoggingBuilder' could be found
Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
// Requires `using Microsoft.Extensions.Logging;`
// logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
})
.UseApplicationInsights()
.UseStartup<StartupConsole>()
.UseDefaultServiceProvider(options => options.ValidateScopes = false);
I am currently using .net-core 2.1 and have nuget for using Microsoft.Extensions.Logging installed.
Make sure you have installed the Microsoft.Extensions.Logging.EventSource NuGet package.
Reference: Logging in .NET Core and ASP.NET Core

Resources