Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage. TypeMappingSourceDependencies' - entity-framework

I ran into the following error after my .net core project and its dependencies to the latest framework version (version 6+) when I was running any CLI command (such as dotnet ef add for instance):
Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage. TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal. MySQLTypeMappingSource'.

I found this article which helped solved the issue: https://www.svrz.com/unable-to-resolve-service-for-type-microsoft-entityframeworkcore-storage-typemappingsourcedependencies/
Adding this class to the project:
public class MysqlEntityFrameworkDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddEntityFrameworkMySQL();
new EntityFrameworkRelationalDesignServicesBuilder(serviceCollection)
.TryAddCoreServices();
}
}
Adding this class solved for me.

Related

EF Core tools System.Configuration.ConfigurationManager assembly not found

I am creating a new application that is using EF Core 2 with migrations.
The application itself is .net Framework but the model is in a separate .net core 2.0 assembly. Everything is working fine I have defined a designtime context factory:
public class MyDesignTimeContextFactory : IDesignTimeDbContextFactory<MyContext>
{
public MyContext CreateDbContext(string[] args)
{
return new MyContext("Server=localhost\\SQLEXPRESS;Database=DBName;User ID=Test;Password=0000;");
}
}
And I can generate migrations and apply/revert them to the DB.
Now if I replace hardcoded connection string with a call to config file
return new MyContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionString");
I have an error when calling EF Core tools:
Add-Migration -Project MyProject.Model -Name Initialization
System.IO.FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.1.0 ....,
However the nuget is there and I can access ConfigurationManager in ContextFactory (not the designtime one) with no problem when launching the application itself. Looks like EF core tools are not looking for the dependencies of the model assembly...
Is there something I am missing? Maybe it is not possible to use ConfigurationManager in DesignTime context factory?
Finally the problem was in the application project. I had to add the nuget package for System.Configuration.ConfigurationManager to the .Net Framework app so the PackatManager can find it. A bit weired that it works at runtime but not in "design mode".

Azure Functions: Can compile but cannot run with custom datalayer library

I've tried to come up with a better title but can't.
The issue is I am new to Azure functions but have made a simple one work that writes to a SQL Azure table. Now I've attempted to build the simplest kind of Entity Framework based Datalayer and uploaded it. Right now it is compiled as .Net 4.6 and using EF 6.1.3.
I'm using a connection string as per the second answer here Second answer and have checked it is being retrieved correctly. Update - I also used this guide.
Removing this {#r "D:\home\site\wwwroot\sharedbin\TestDataLayer.dll"} causes the editor to complain about missing assemblies, so it IS finding the dll in question.
However it will not run - it cannot find TestDataLayer.dll.
I'm only running this in the portal editor (I've not yet mastered deployment direct from a Visual Studio Project - don't laugh :P).
#r "System.Configuration"
#r "System.Data.Entity"
#r "D:\home\site\wwwroot\sharedbin\TestDataLayer.dll"
using System;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.SqlServer;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Net;
using TestDataLayer;
public static void Run(TimerInfo myTimer, TraceWriter log)
{
var connection = ConfigurationManager.ConnectionStrings["sql_connection"].ConnectionString;
using(var db = new SyncDbContext(connection))
{
var RK = new RKAzureTest() {TestField1 = "It finally worked?" };
db.RKAzureTests.Add(RK);
db.SaveChanges();
}
}
[DbConfigurationType(typeof(myDBContextConfig))]
public partial class SyncDbContext : System.Data.Entity.DbContext
{
public SyncDbContext(string cs) : base(cs) {}
public DbSet<RKAzureTest> RKAzureTests {get;set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class myDBContextConfig : DbConfiguration
{
public myDBContextConfig()
{
SetProviderServices("System.Data.EntityClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlConnectionFactory());
}
}
This is the function.json:
{
"frameworks": {
"net46":{
"dependencies": {
"EntityFramework": "6.1.3"
}
}
}
}
I've compiled the dll itself to .Net 4.6 after a suspicion that the Azure Functions don't support .net 4.7.1 and via Kudu uploaded the compiled dll to a sharedbin folder (checked the path a dozen times!).
This is the error thrown up:
2018-05-01T11:00:00.012 [Warning] Unable to find assembly 'TestDataLayer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Are you missing a private assembly file?
2018-05-01T11:00:00.012 [Error] Exception while executing function: Functions.TimerTriggerCSharp1. mscorlib: Exception has been thrown by the target of an invocation. f-TimerTriggerCSharp1__514732255: Could not load file or assembly 'TestDataLayer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Not quite sure what else can be left - I'm using runtime version 1.0.11702 in the Application settings as I found life got a LOT more complicated if I went onto the Beta version.
If anyone can point me to a working guide for this use case (Database first, EF 6.1.3 etc) I'd be grateful.
Any help offered gratefully received!
Thank you :)
Go to Azure Portal, create a folder called, 'bin' inside your Azure functions using CMD Shell, upload the 'TestDataLayer.dll' file to bin folder which has just been created.
#r "System.Configuration"
#r "System.Data.Entity"
#r "TestDataLayer.dll"
Project structure should look like,
AzureFunctionProjectName001
bin
TestDataLayer.dll
run.csx
project.json
project.lock.json
...
Azure functions should be able to discover your library this time. I believe, EntityFramework works just fine.

Entity Framework Core 2 context and model in separate project to main project

How do i add-migrations into a separate data project??
I've got two projects, a data project with the context and models in and the website project which will use it. I've linked the two together all fine and dandy, the problem is that when I try and add a migration to the data project with add-migration initialmigration, the error
Unable to create an object of type 'myContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
The link has details on how to add the IDesignTimeDbContextFactory but which doesn't work because UseSqlServer doesn't exist as a command. That page does link to the updated version at https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#update-main-method-in-programcs which says to put code into program.cs Even if I follow the instructions and add it to my data project (along with the associated references) so that I include
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
which is what it says to do, but I get the same error message. So, regardless of whether I include the section of code or not I get the same error message, despite the Microsoft.com page stating that the above code stops the error message I'm getting from appearing.
I've tried putting the context and model into my main project and that generates migrations fine, so the code for those is fine at least.
How do i add-migrations into a separate data project??
Add-Migration has a -Project parameter.
Add-Migration -Project MyProject -Context MyDbContext -Name InitialMigration
EDIT: To see all options for a cmdlet (since Package Manager Console is just PowerShell) do
Get-Help Add-Migration -Full
Your DbContext in class library should look like this:
public class ExampleDbContext : DbContext
{
public UserProfileDbContext(DbContextOptions<ExampleDbContext > options)
: base(options) { }
public DbSet<Example> Examples{ get; set; }
}
And in your Startup you should add:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ExampleDbContext >(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
}
This is when you are using MS Sql server and have connection string in appsettings.json
Then for example use package manager console for your class library project with EF and it should work.
You should have following nuget packages in you class library project:
Microsoft.EntityFrameworkCore,
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

Nunitlite-runner.exe - Dll file has no TestFixtures

I'm trying run tests from nunitlite-runner.exe but i got Error message
1) Invalid : /myfile.dll
Has no TestFixtures
I have in source code
[TestFixture]
public class MyClassName
{
[Order(1)]
[Test]
public void Case1()
{
//
}
[Order(2)]
[Test]
public void Case2()
{
//
}
}
How can i fix code or run my tests?
I got this problem with nunit3-console.exe. I had, in my enthusiasm to upgrade to the latest and greatest, updated my NUnit project references to the latest version (3.9 at this writing), along with my console exe (3.7). But it seems that the console exe is a build or two behind the core libraries, so you can't reference a later version of NUnit than the version you have of the console exe.
I downgraded my NUnit project reference to 3.7, and that fixed it for me.

Entity Framework 5.0 RC - Package Manager command 'add-migration' fails due to supposedly missing configuration type

Using Entity Framework 5.0.0 RC/EF 5.x DbContext Generator for C#/Visual Studio 2012 RC/.NET 4.0, I'm trying to enable automatic migrations in my project. I've run enable-migrations in the Package Manager Console:
PM> enable-migrations
No classes deriving from DbContext found in the current project.
Edit the generated Configuration class to specify the context to enable migrations for.
Code First Migrations enabled for project Test.
As you can see, it didn't automatically detect my DbContext derived type, but I solved this easily enough by entering the name of this type in the generated code file, Migrations/Configuration.cs.
However, the next step, the Package Manager Console command enable-migrations fails due to not finding the migrations configuration type added by the previous step.
PM> add-migration Initial
No migrations configuration type was found in the assembly 'Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
How can I solve this?
EDIT: I found that I could specify the name of the configuration type with the parameter -ConfigurationTypeName:
PM> add-migration -ConfigurationTypeName Test.Migrations.Configuration Initial
The type 'Configuration' is not a migrations configuration type.
This still doesn't work, but at least it elucidates why add-migration bails, i.e. it thinks Test.Migrations.Configuration isn't a migrations configuration type. Does anyone have a clue as to why it isn't accepted, given that it was generated by enable-migrations? See the generated code below for reference (UserModelContainer derives from DbContext):
namespace Test.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Test.Models;
internal sealed class Configuration : DbMigrationsConfiguration<UserModelContainer>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(UserModelContainer context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
The issue turned out to be that I had installed Entity Framework 5.0.0 RC while targeting .NET framework 4.5. Due to deploying to Windows Azure, I found I had to target .NET 4.0 instead. I don't know the intricacies of NuGet, but it seems that the EF package installed for .NET 4.5 didn't work properly with my 4.0 targeting project.
After reinstalling the EF NuGet package, while targeting my project at .NET 4.0, everything works well.