3

In Visual Studio I have an Azure Function, written in C#, which is supposed to read from an Azure SQL database using Entity Framework (EF6).

I cannot get Entity Framework to work. When I publish the Azure Function I get the error:

The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715

None of this worked.

I also tried to add a project.json file in Azure as recommended by many websites but that didn’t change anything.

Here is the C#.

public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("*/100 * * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        try {
            using (var qc = new quotecandyEntities()) {

                if (qc.Users.Any()) {
                    log.Info($"The last user is {qc.Users.Last().Email}.");

                } else {
                    log.Info("No users found in database.");
                }
            }
        } catch (Exception ex) {
            log.Error($"Error: {ex.Message}");
        }
    }
}
Jan_V
  • 4,244
  • 1
  • 40
  • 64
Hank Tuff
  • 185
  • 5
  • 12
  • Was the edml dll got deployed along with the package from Visual Studio. May be the class related to quotecandyEntities() are not copied. – Baskar Rao Nov 21 '17 at 06:01
  • I am relatively new to Azure. Where do I see what files were deployed? – Hank Tuff Nov 21 '17 at 06:16
  • You can use kudu browser to see which files got deployed. Kudu can be accessed by https://functionappname.scm.azurewebsites.net – Baskar Rao Nov 21 '17 at 06:58
  • You can use kudu browser to see which files got deployed. Kudu can be accessed by https://functionappname.scm.azurewebsites.net Once in Kudu you can go to debug console - select cmd. This will open a bash window. https://blogs.msdn.microsoft.com/uk_faculty_connection/2017/05/15/using-kudu-and-deploying-apps-into-azure/ This gives an overview of kudu – Baskar Rao Nov 21 '17 at 07:03
  • Under D:\home\site\wwwroot\bin\ I see these files: Dolaris.QuoteCandy.EDM.dll, Dolaris.QuoteCandy.EDM.dll.config EntityFramework.dll, EntityFramework.SqlServer.dll, EntityFramework.xml, Microsoft.Data.Edm.dll, Microsoft.Data.OData.dll – Hank Tuff Nov 21 '17 at 22:15

2 Answers2

6

According to your description, I assumed that you are using Database First or Model First, and you configured the wrong Entity Framework connection string for your Entity Data Model. I tested and found that if my directly copy the connection string from Azure Portal while I am using Database First, I would encounter the similar issue you provided as follows:

enter image description here

For Database First, I would recommend you modify the generated Model.Content.cs and configure your DbContext as follows:

public partial class Entities : DbContext
{
    public Entities():base(ConfigurationManager.ConnectionStrings["Entities"].ConnectionString)
    {

    }
}

Note: You could modify the t4 template and make sure you modification for your DbContext does not overridden after you updated the model from your database.

For dev, you could set your connection string under local.settings.json file as follows:

"ConnectionStrings": {
  "Entities": "metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source={server-name}.database.windows.net;initial catalog={db-name};persist security info=True;user id={username};password={password};MultipleActiveResultSets=True;App=EntityFramework'"
}

Before publishing to azure, you could create a connection string with the same as you configured under local.settings.json file and set the connection string as follows:

enter image description here

Moreover, you could follow this similar issue about the approach for using EF Database First in Azure Function.

Bruce Chen
  • 18,207
  • 2
  • 21
  • 35
  • Adding the connection string in the code itself, instead of the settings, worked! Thank you! – Hank Tuff Nov 23 '17 at 22:35
  • This worked for me. Just an small addition, I had to add a `using System.Configuration` statement to my tt/cs file as well as adding an assembly reference as my Data project did not reference this dll. Thanks! – Chris Morledge Jan 31 '18 at 00:25
1

since i had hard time setting this even with post here is the complete version

project1 (azure function) : local.settings.json

  {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
        "schedule": "*/1 * * * * *"
      },
      "ConnectionStrings": {
        "dbEntities": "metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source=someAzureServer.database.windows.net;initial catalog=someDB;persist security info=True;user id=foo;password=XXXX;MultipleActiveResultSets=True;App=EntityFramework'",
        "ProviderName": "System.Data.EntityClient"
      }

    }

Project2(dll): Model1.Context.cs

namespace main2
{
    using System;
    using System.Configuration;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class dbEntities : DbContext
    {
        public crypto_dbEntities()
            : base(ConfigurationManager.ConnectionStrings["dbEntities"].ConnectionString)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
}

now rename : -connectionstring name -server name -db name -user name -password

so i remember later too;)

Zwan
  • 632
  • 2
  • 6
  • 23