Azure Functions Database Connection String

前端 未结 14 683
谎友^
谎友^ 2020-12-05 17:08

How do I add or access an app.config file in Azure functions to add a database connection string?

If you\'re not supposed to add an app.config

相关标签:
14条回答
  • 2020-12-05 17:42

    I went through several similar questions and answers here. Many of them are either misleading or assuming everybody is on the same level and understands how the azure functions are working. there is no answer for newbies like me. I would like to summarize here my solution step by step.

    1. most important thing is that we understand local.settings.json file IS NOT FOR AZURE. it is to run your app in the local as the name is clearly saying. So solution is nothing to do with this file.

    2. App.Config or Web.Config doesnt work for Azure function connection strings. If you have Database Layer Library you cant overwrite connection string using any of these as you would do in Asp.Net applications.

    3. In order to work with, you need to define your connection string on the azure portal under the Application Settings in your Azure function. There is Connection strings. there you should copy your connection string of your DBContext. if it is edmx, it will look like as below. There is Connection type, I use it SQlAzure but I tested with Custom(somebody claimed only works with custom) works with both.

    metadata=res:///Models.myDB.csdl|res:///Models.myDB.ssdl|res://*/Models.myDB.msl;provider=System.Data.SqlClient;provider connection string='data source=[yourdbURL];initial catalog=myDB;persist security info=True;user id=xxxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework

    1. After you set this up, You need to read the url in your application and provide the DBContext. DbContext implements a constructor with connection string parameter. By default constructor is without any parameter but you can extend this. if you are using POCO classes, you can amend the DbContext class simply. If you use Database generated Edmx classes like I do, you don't want to touch the auto generated edmx classes, instead you want to create partial class in the same namespace and extend this class as below.

    This is auto generated DbContext

    namespace myApp.Data.Models
    {   
    
        public partial class myDBEntities : DbContext
        {
            public myDBEntities()
               : base("name=myDBEntities")
            {
            }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                throw new UnintentionalCodeFirstException();
            }
    
    }
    

    this is the new partial class, you create

    namespace myApp.Data.Models
    {
        [DbConfigurationType(typeof(myDBContextConfig))]
        partial class myDBEntities
        {
    
            public myDBEntities(string connectionString) : base(connectionString)
            {
            }
        }
    
          public  class myDBContextConfig : DbConfiguration
            {
                public myDBContextConfig()
                {
                    SetProviderServices("System.Data.EntityClient", 
                    SqlProviderServices.Instance);
                    SetDefaultConnectionFactory(new SqlConnectionFactory());
                }
            }
        }
    
    1. After all you can get the connection string from azure settings, in your Azure Function project with the code below and provide to your DbContext myDBEntities is the name you gave in the azure portal for your connection string.
    var connString = ConfigurationManager.ConnectionStrings["myDBEntities"].ConnectionString;
    
    
     using (var dbContext = new myDBEntities(connString))
    {
            //TODO:
    }
    
    0 讨论(0)
  • 2020-12-05 17:43

    Addition to the answer from @ToddDeLand.

    With a local.settings.json like this:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true;",
        "AzureWebJobsDashboard": ""
      },
      "ConnectionStrings": {
        "MyConnectionString": "[YourConnectionStringHere]"
      }
    }
    

    You can then access your connection string like this, no NuGets needed.

    var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:MyConnectionString");
    

    Microsoft recommends this approach here:

    https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables

    If you add the connection string to values:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true;",
        "AzureWebJobsDashboard": "",
        "MyConnectionString": "[YourConnectionStringHere]"
      }
    }
    

    You can access your connection string like this:

    var connectionString = Environment.GetEnvironmentVariable("MyConnectionString");
    

    Sources:

    https://stackoverflow.com/a/52219491/3850405

    https://github.com/Azure/Azure-Functions/issues/717#issuecomment-400098791

    0 讨论(0)
提交回复
热议问题