EF Core tools System.Configuration.ConfigurationManager assembly not found - entity-framework

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".

Related

How to tell entitiy framework that my db context class is avaiable in core project to run the migration in diffrent project?

Dear Developers,
I am new to EF.
I have this project srtucture.
+ HrSoultion
+ <Application> // namespace project
- api // this is the mvc core project
+ <Core> // namespace project
- Entity// this is the project where I defined the models and db context class
Now I am confused where to run the add Add-Migration HrSoultion.Core.HrSoultionContext
Thanks ?
Option 1: Use command line
dotnet ef migrations add Init
Option 2: Select appropriate project before you run Add-Migration command in Package Manager Console. E.g.

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.

Is there a way to migrate EF in .netstandard with Xamarin.Forms package?

I have a .netstandard Model layer that referenced from Xamarin.forms.
I set Xamarin.Forms package in Model layer => PrivateAssets="All".
My .netstandard Data layer referenced from Model layer.
When I run this command in PowerShell :
dotnet ef --startup-project ../Eela.Web/ migrations add v1
I have this error :
C:\Users*.nuget\packages\xamarin.forms\2.3.4.231\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+Xamarin.iOS10+xamarinmac20\Xamarin.Forms.targets(40,3): error MSB4062: The
"Xamarin.Forms.Build.Tasks.FixedCreateCSharpManifestResourceName" task
could not be loaded from the assembly
C:\Users*.nuget\packages\xamarin.forms\2.3.4.231\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+Xamarin.iOS10+xamarinmac20\Xamarin.Forms.Build.Tasks.dll.
Could not load file or assembly 'Microsoft.Build.Utilities.v4.0,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
The system cannot find the file specified. Confirm that the
declaration is correct, that the assembly and all its dependencies are
available, and that the task contains a public class that implements
Microsoft.Build.Framework.ITask. [.....\Eela.Model.csproj]
Even I'm using :
<PackageTargetFallback>$(PackageTargetFallback);portable-win+net45+wp8+win81+wpa8</PackageTargetFallback>
in Data layer but the problem is persisted,
Is there any way to resolve this problem ?
I did not use the migrations with EntityFramework core in a xamarin forms app. I just used
await db.Database.EnsureCreatedAsync()
If you add a .net core console app to the solution I think you can you can use migrations.

Can't load Entity Framework Core in Azure Function

I'm trying to use Entity Framework Core with a C# Azure Function, and I'm getting tons of errors with libraries. Starting from the default HTTP trigger template, I created a project.json file containing
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0"
}
}
}
}
When the package restore finishes, the compiler can no longer find the extension methods in HttpRequestMessageExtensions:
016-12-21T06:59:24.728 (9,19): error CS1929: 'HttpRequestMessage' does
not contain a definition for 'GetQueryNameValuePairs' and the best
extension method overload
'HttpRequestMessageExtensions.GetQueryNameValuePairs(HttpRequestMessage)'
requires a receiver of type 'HttpRequestMessage'
(and 3 other similar errors).
I don't really need to use those extension methods, and if I delete all code that calls them, instead I get errors about the version of System.Net.Http:
Exception during runtime resolution of assembly 'System.Net.Http,
Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a':
'System.BadImageFormatException: Cannot load a reference assembly for
execution.
at System.Reflection.RuntimeAssembly.nLoadFile(String path,
Evidence evidence)
at System.Reflection.Assembly.LoadFile(String path)
at
Microsoft.Azure.WebJobs.Script.Description.FunctionMetadataResolver.ResolveAssembly(String
assemblyName)
at
Microsoft.Azure.WebJobs.Script.Description.FunctionAssemblyLoadContext.ResolveAssembly(String
name)
at
Microsoft.Azure.WebJobs.Script.Description.FunctionAssemblyLoader.ResolveAssembly(Object
sender, ResolveEventArgs args)'
2016-12-21T07:00:00.522 Unable to find assembly 'System.Net.Http,
Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Are you missing a private assembly file?
When NuGet adds the EntityFrameworkCore package, it installs System.Net.Http version 4.3.0, whereas Azure Functions seems to be looking for the hardcoded version 4.1.1.
I see questions about using EF6 with Azure Functions, but I don't see anything about EF Core.
one solution is changing from Azure Function v2 core to Azure Function v1 framework.

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.