【问题标题】:Unable to connect Azure Function App with Database (using .net core 2.1)无法将 Azure Function App 与数据库连接(使用 .net core 2.1)
【发布时间】:2019-12-29 13:24:28
【问题描述】:

请注意(环境): 功能应用程序:版本 2, 目标框架:.Net Core 2.1

我正在开发一个功能应用程序,它将像 Web Api 一样工作。此函数应用程序将从数据库表中返回数据,还将操作 Azure 存储(Blob)中的文件。但我被卡住了,因为我无法从 local.settings.json 文件创建 ConnectionString。理想情况下,应该默认创建连接字符串,因为我遵循了一些教程并且没有提到创建默认 connectionstring 值的任何额外步骤,只需要在 local.settings.json 中创建它强> 文件。

以下是我的 local.settings.json 文件内容:-

    {
  "ConnectionStrings": {
    "mycs": "data source=servername;initial catalog=dbname;user id=XXXX;password=XXXX;MultipleActiveResultSets=True;"
  },
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "mycs": "data source=servername;initial catalog=dbname;user id=XXXX;password=XXXX;MultipleActiveResultSets=True;"
  }
}

以下是我的 HttpTrigger 文件:

    namespace my_api
    {
        public class myDataContext : DbContext
        {
            public myDataContext() : base(GetConnectionString()) { }
            private static string GetConnectionString()
            {

                const string providerName = "System.Data.SqlClient";
                const string metadata = @"res://*/MYDB.csdl|res://*/MYDB.ssdl|res://*/MYDB.msl";
                try
                {
                    string connectString = ConfigurationManager.ConnectionStrings["mycs"].ToString();


                    // Initialize the connection string builder for the
                    // underlying provider.
                    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(connectString);

                    // Set the properties for the data source.
                    //sqlBuilder.IntegratedSecurity = true;
                    sqlBuilder.MultipleActiveResultSets = true;

                    // Build the SqlConnection connection string.
                    string providerString = sqlBuilder.ToString();

                    // Initialize the EntityConnectionStringBuilder.
                    EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();

                    //Set the provider name.
                    entityBuilder.Provider = providerName;

                    // Set the provider-specific connection string.
                    entityBuilder.ProviderConnectionString = providerString;

                    // Set the Metadata location.
                    entityBuilder.Metadata = metadata;

                    return entityBuilder.ConnectionString;
                }
                catch { }

                var connectionstring = Environment.GetEnvironmentVariable("mycs");
                return connectionstring;
            }

            public DbSet<flowerset> flowersets
            {
                get;
                set;
            }
        }
    }

以下是代码:

namespace my_api

{ 公共静态类 helpService { [函数名(“helpService_get”)] 公共静态异步任务>运行( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger 日志,ExecutionContext 上下文) { log.LogInformation("C# HTTP 触发函数处理了一个请求 helpService_get).");

        try {
            int page = 0;
            int pageSize = 20;

            myDataContext entity = new myDataContext();
            if (page == 0 && pageSize == 0)
            {
                return entity.helpsets.ToList();
            }
            if (pageSize <= 0) { pageSize = 20; }
            entity.helpsets.OrderByDescending(x => x.id).Skip((page - 1) * pageSize).Take(pageSize).ToList();
        }
        catch (Exception exx) {
            log.LogInformation("Exception changed (helpService_get): "+exx.Message);
        }
        return null;
    }

}//End of Class
}//End of Namespace

我在 entity.helpsets.OrderByDescending(x => x.id).Skip((page - 1) * pageSize).Take(pageSize).ToList(); 行遇到以下错误;

Unable to determine the provider name for provider factory of type 'System.Data.SqlClient.SqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.

【问题讨论】:

  • 根据你的错误,我认为你没有安装包System.Data.SqlClient。请问你是否在你的函数项目中安装了这个包?
  • 是的,System.Data.SqlClient 包已安装,我看到此错误,因为 Function App 2.0 是 .net 核心应用程序,似乎不支持 ADO.net 或可能是我不知道其他解决方案。

标签: asp.net-core azure-functions asp.net-core-2.1


【解决方案1】:

根据我的测试,我们可以在Azure函数V2.0中使用System.Data.SqlClient连接Azure SQL。例如

  1. 使用 Visual Studio 2019 创建 Azure 函数
  2. 安装System.Data.SqlClient包(我申请的版本是4.5.1)
  3. 开发功能

local.settings.json 文件内容

  "ConnectionStrings": {
    "mycs": "Data Source="";Initial Catalog=DotNetAppSqlDb20190826105048_db;User Id="";Password="" "
  },

  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

代码

[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;
            try
            {
                var connectionstring = System.Environment.GetEnvironmentVariable($"ConnectionStrings:mycs"); ;



                using (SqlConnection connection = new SqlConnection(connectionstring))
                {


                    connection.Open();
                    log.LogInformation(" sql login success");
                    StringBuilder sb = new StringBuilder();
                    sb.Append("select * from dbo.Todoes");

                    String sql = sb.ToString();

                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                log.LogInformation("{0} {1}", reader.GetInt32(0), reader.GetString(1));
                            }
                        }
                    }
                    connection.Close();
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }
            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

更多详情请参考document

【讨论】:

  • @user1400290 你可以吗?您还有其他顾虑吗?
猜你喜欢
  • 2020-04-04
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多