gpt4 book ai didi

c# - Visual Studio 中的 Azure Function 中的 Entity Framework

转载 作者:行者123 更新时间:2023-11-30 14:22:57 26 4
gpt4 key购买 nike

在 Visual Studio 中,我有一个用 C# 编写的 Azure 函数,它应该使用 Entity Framework (EF6) 从 Azure SQL 数据库中读取。

我无法让 Entity Framework 工作。当我发布 Azure Function 时,出现错误:

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

这些都不起作用。

我还尝试按照许多网站的建议在 Azure 中添加一个 project.json 文件,但这并没有改变任何内容。

这是 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}");
}
}
}

最佳答案

根据您的描述,我假设您使用的是数据库优先或模型优先,并且您为实体数据模型配置了错误的 Entity Framework 连接字符串。我测试发现,如果我在使用 Database First 时直接从 Azure Portal 复制连接字符串,我会遇到您提供的类似问题,如下所示:

enter image description here

对于 Database First,我建议您修改生成的 Model.Content.cs 并配置 DbContext,如下所示:

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

}
}

注意:您可以修改 t4 模板,并确保在从数据库更新模型后,对 DbContext 的修改不会被覆盖。

对于开发人员,您可以在 local.settings.json 文件下设置连接字符串,如下所示:

"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'"
}

在发布到 azure 之前,您可以创建一个与您在 local.settings.json 文件中配置的连接字符串相同的连接字符串,并按如下方式设置连接字符串:

enter image description here

此外,您可以关注类似的 issue关于在Azure Function中使用EF Database First的方法。

关于c# - Visual Studio 中的 Azure Function 中的 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47406100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com