Enable-Migrations "Object reference not set to an instance of an object" - entity-framework

I just created a new service fabric service that will periodically attempt to save some models to SQL Azure using Entity Framework and the Elastic Client Database library. I'm trying to model it as closely as I can to the SQL Azure Elastic Scale Client Library EF sample (Elastic DB Tools EF Sample). I'm at the point where I need to enable migrations, but when I run Enable-Migrations I'm getting the following error message. I'm using the ContextTypeName parameter since it sounded like it would be required if I'm going to eventually have different service fabric services targeting the same database with different models. Any suggestions?
PM> Enable-Migrations -ContextTypeName "ServiceHealth.DbService"
Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
not marked as serializable."
At C:\eNowCloud\eNow.MicroServices\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:720 char:5
+ $domain.SetData('startUpProject', $startUpProject)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SerializationException
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetProjectTypes(Project project, Int32 shellVersion)
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.IsWebProject(Project project)
at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.

I have resolved the same exception issue by specifying -StartUpProjectName parameter of Enable-Migrations command to my .NET framework dll with the db context. The issue might be with the weird startup project - problem in .IsWebProject() (asp.core in my case). See more detail answer on Enable-Migrations Exception calling "SetData" with "2" argument(s).

If you are using visual studio 2019, when you want to add a new class library you face to kind of class library:
Class Library (.NET Standard)
Class Library (.NET Framework)
Well, I used to pick number1, but now I know I have made mistake.
The solution is to Pick number2.

Instead of Enable-Migrations Do this EntityFrameworkCore\Enable-Migrations
Use EntityFrameworkCore\ before any command.
PS: Using VisualStudio 2019

Related

EF Core Power Tools EntityFrameworkCore.Design.OperationException suddenly occurring on "Add DbContext Diagram"

I've been using EF Core Power Tools to assist with learning EF Core. The data project is simply a class library that contains the base DbContext used by the associated web app, plus the migrations folder.
It's been working fine until suddenly this error occurs when I "Add DbContext Diagram"
System.InvalidOperationException: Error:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EventFinderContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[EventFinderData.EventFinderContext]' while attempting to activate 'EventFinderData.EventFinderContext'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Modelling.EfCoreModelBuilder.BuildResult(String outputPath, String startupOutputPath, Boolean generateDdl) in C:\Code\EFCorePowerTools\src\GUI\efpt30.core\EFCoreModelBuilder.cs:line 41
at Modelling.Program.Main(String[] args) in C:\Code\EFCorePowerTools\src\GUI\efpt30.core\Program.cs:line 56
at async Task EFCorePowerTools.Handlers.ModelAnalyzerHandler.GenerateAsync(string outputPath, Project project, GenerationType generationType)
I'm not sure even where to start looking to investigate, so any pointers would be appreciated please. The solution builds okay, the database seems fine, and the associated Blazor project also runs fine.
Not sure if its helpful but in my data project, the constructor for the DbContext is this:
namespace EventFinderData
{
public class EventFinderContext : DbContext
{
public EventFinderContext(DbContextOptions<EventFinderContext> options) : base(options)
{
}
}
}
You have to register EventFinderContext in program.cs
builder.Services.AddDbContext<EventFinderContext>(
opt => opt.UseSqlServer("Your_connection_string"));
As advised by ErikEJ (the author of Power Tools) the diagram function only works on the executable project. Once I had added a web application project to my solution, the original console and data layer projects in that solution no longer worked for creating the diagram.

Unable to load DLL 'sni.dll' or one of its dependencies: Access is denied. (0x80070005 (E_ACCESSDENIED))

I'm trying to use Entity Framework Core 3.1.7 (code first) with SQL Server Express.
add-migration works well but when I try to migrate to the database I
System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.TdsParser' threw an exception.
---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception.
---> System.DllNotFoundException: Unable to load DLL 'sni.dll' or one of its dependencies: Access is denied. (0x80070005 (E_ACCESSDENIED))
at Microsoft.Data.SqlClient.SNINativeMethodWrapper.SNIInitialize(IntPtr pmo)
at Microsoft.Data.SqlClient.SNINativeMethodWrapper.SNIInitialize()
at Microsoft.Data.SqlClient.SNILoadHandle..ctor()
at Microsoft.Data.SqlClient.SNILoadHandle..cctor()
--- End of inner exception stack trace ---
at Microsoft.Data.SqlClient.TdsParserStateObjectFactory.get_EncryptionOptions()
at Microsoft.Data.SqlClient.TdsParser..cctor()
--- End of inner exception stack trace ---
If I look for the file, it is there under ..\bin\Debug\netcoreapp3.1\runtimes\win-x64\native\
btw
Did try installing Microsoft.Data.SqlClient Nuget package but get the same error different
After a day and a half, I figure it out. It was the connection string (I'm using SQL Server Express) I changed 'localhost' for the computer's name and it worked.

Could not load file or assembly 'Microsoft.PowerShell.Security' or one of its dependencies. The system cannot find the file specified

I'm running PowerShell from a C# console app. My dev box has PowerShell 3.0 - the target machines will probably have v2.0. My project file has a reference to the assembly:
<Reference Include="System.Management.Automation" />
which seems to be the recommended way. I'm getting a System.IO.FileNotFoundException when I call runspace.Open():
using (var runspace = RunspaceFactory.CreateRunspace(initialSessionState))
{
runspace.AvailabilityChanged += runspace_AvailabilityChanged;
runspace.StateChanged += runspace_StateChanged;
runspace.Open();
...
}
The exception details are:
Message: Could not load file or assembly 'Microsoft.PowerShell.Security' or one of its dependencies. The system cannot find the file specified.
FusionLog:
=== Pre-bind state information ===
LOG: User = MYDOMAIN\MyUser
LOG: DisplayName = Microsoft.PowerShell.Security
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Microsoft.PowerShell.Security | Domain ID: 1
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/MyUser.MYDOMAIN/Projects/PoSh/PoShRunner1/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\MyUser.MYDOMAIN\Projects\PoSh\PoShRunner1\bin\Debug\PoShRunner1.vshost.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/MyUser.MYDOMAIN/Projects/PoSh/PoShRunner1/bin/Debug/Microsoft.PowerShell.Security.DLL.
LOG: Attempting download of new URL file:///C:/Users/MyUser.MYDOMAIN/Projects/PoSh/PoShRunner1/bin/Debug/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.DLL.
LOG: Attempting download of new URL file:///C:/Users/MyUser.MYDOMAIN/Projects/PoSh/PoShRunner1/bin/Debug/Microsoft.PowerShell.Security.EXE.
LOG: Attempting download of new URL file:///C:/Users/MyUser.MYDOMAIN/Projects/PoSh/PoShRunner1/bin/Debug/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.EXE.
If I turn off Common Language Runtime Exceptions in VS 2012, I get
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.DllNotFoundException' occurred in System.Management.Automation.dll
A first chance exception of type 'System.Management.Automation.Host.HostException' occurred in System.Management.Automation.dll
in the output log.
I've had a look at the document referenced in the fusion log but most of it doesn't seem to apply to this case or help much with my understanding. Microsoft.PowerShell.Security is in the GAC so what's the problem?
The problem is that you compiled against the powershell 3.0 system.management.automation (s.m.a.) assembly - 3.0.0.0 - instead of the powershell 2.0 s.m.a which is 1.0.0.0.
Open your project, browse to the 1.0.0.0 version and recompile. PowerShell 3.0 installs both 1.0.0.0 and 3.0.0.0 s.m.a assemblies to the GAC. Then your program will work on systems with either 2.0 or 3.0 versions of powershell.

Object.GetType throws NullReferenceExceptions

I'm trying to use Pex and Moles in my SharePoint project. However I'm facing problem when running Pex Explorations. I'm getting error:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Type System.Object.GetType()
Additionaly in "Pex Exporations result" window i'm seeing 2 Reflection issues:
System.TypeLoadException: Method 'get_TargetType' in type 'System.ComponentModel.Moles.SBaseNumberConverter' from assembly 'System.Moles, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0ae41878053f6703' does not have an implementation.
at an attribute that decorates
[module System.Moles.dll]
and
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at an attribute that decorates
[module System.Moles.dll]

Code-First Entity Framework - error creating SQL CE DB

I have been using Entity Framework CTP with Code-First as in this tutorial by Scott Guthrie and another by Scott Hanselman (can't post the link, but google "Simple Code First with Entity Framework 4 - Magic Unicorn Feature CTP 4"). This is working perfectly for the main MVC application, but I am now trying to add a testing project, that uses a separate SQL CE Database.
I have added the following to the App.Config file:
<connectionStrings>
<add name="MyData"
connectionString="Data Source=D:\myProject\myDb.sdf;"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
However when I try to run the tests it throws the following error when trying to create the database:
Test method
MyProjet.Tests.Administration.ModlelTests.Business.TestGetBusinessesList
threw exception:
System.Reflection.TargetInvocationException:
Exception has been thrown by the
target of an invocation. --->
System.TypeInitializationException:
The type initializer for
'System.Data.SqlServerCe.SqlCeProviderServices'
threw an exception. --->
System.Security.VerificationException:
Operation could destabilize the
runtime.
With the following stack trace:
System.Data.SqlServerCe.SqlCeProviderServices..ctor()
System.Data.SqlServerCe.SqlCeProviderServices..cctor()
System.RuntimeFieldHandle.GetValue(RtFieldInfo
field, Object instance, RuntimeType
fieldType, RuntimeType declaringType,
Boolean& domainInitialized)
System.Reflection.RtFieldInfo.InternalGetValue(Object
obj, Boolean doVisibilityCheck,
Boolean doCheckConsistency)
System.Reflection.RtFieldInfo.InternalGetValue(Object
obj, Boolean doVisibilityCheck)
System.Reflection.RtFieldInfo.GetValue(Object
obj)
System.Data.SqlServerCe.ExtensionMethods.SystemDataSqlServerCeSqlCeProviderServices_Instance_GetValue()
System.Data.SqlServerCe.ExtensionMethods.SystemDataSqlServerCeSqlCeProviderServices_Instance()
System.Data.SqlServerCe.SqlCeProviderFactory.System.IServiceProvider.GetService(Type
serviceType)
System.Data.Common.DbProviderServices.GetProviderServices(DbProviderFactory
factory)
System.Data.Common.DbProviderServices.GetProviderServices(DbConnection
connection)
System.Data.Entity.ModelConfiguration.Internal.Configuration.CodeFirstCachedMetadataWorkspace.GetMetadataWorkspace(DbConnection
storeConnection)
System.Data.Entity.Infrastructure.DbModel.CreateObjectContext[TContext](DbConnection
existingConnection)
System.Data.Entity.Internal.LazyInternalContext.InitializeFromModel(DbModel
model)
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
System.Data.Entity.Internal.InternalContext.Initialize()
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType)
System.Data.Entity.Internal.Linq.EfInternalQuery1.Initialize()
System.Data.Entity.Internal.Linq.EfInternalQuery1.Include(String
path)
System.Data.Entity.Infrastructure.DbQuery`1.Include(String
path)
MyProjet.Areas.Administration.Models.BusinessModel.GetBusinesses()
in
D:\projects2010\MyProjet\MyProjet\Areas\Administration\Models\BusinessModel.cs:
line 47
MyProjet.Tests.Administration.ModlelTests.Business.TestGetBusinessesList()
in
D:\projects2010\MyProjet\MyProjet.Tests\Administration\ModlelTests\Business.cs:
line 45
I have tried replacing the existing MyData connection string in the MVC application, and it works fine. It only causes this problem when this is added to the Testing project. Additionally the testing project works without problem when pointed at an SQL or SQL Express Database.
Have been struggling with this for a while now, and just can't figure it out. I am sure I have overlooked something simple.
Try using
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
See my blog post for an example http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/
I have been running the tests under the Built in Microsoft testing framework. Changing the test framework to NUnit (as in Jag's tutorial) has fixed the problem.
So looks like there is a conflict between SqlServerCe and the Visual Studio Unit Testing Framework.