Azure 函数中 Entity Framework 的连接字符串

Connection string for Entity Framework in an Azure Function

我正在创建一个 Azure 函数,并且添加了对使用 Entity Framework 的项目的引用。我已经从该项目复制了连接字符串,并将其作为有效的 EF 连接字符串粘贴到 ConnectionStrings 对象内的 local.settings.json 文件中。

metadata=res://*/xxx.csdl|res://*/xxx.ssdl|res://*/xxx.msl;
provider=System.Data.SqlClient;
provider connection string=&quote;
    data source=xxx;
    initial catalog=xxx;
    user id=xxx;
    password=xxx;
    MultipleActiveResultSets=True;
    App=EntityFramework
&quote;

但它给了我这个例外:

Keyword not supported: metadata.


如果我使用有效的 SQL 连接字符串 (如下所示),

data source=xxx;
initial catalog=xxx;
user id=xxx;
password=xxx;
MultipleActiveResultSets=True;
App=EntityFramework

我有这个例外:

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


如何使用 Entity Framework 在 Azure 函数中创建到我的数据库的连接?我正在使用 .NET 框架,对于 EF,我首先使用数据库。


我正在如下初始化我的数据库上下文:

using (XxxDB db = new XxxDB()) 
{ }

与此同时,我为委托人创建了一个重载 XxxDB

public XxxDB(string connectionString): base(new EntityConnection(connectionString), true)
{ }

并在创建 XxxDB 时传递 SQL 连接字符串并出现此错误:

Keyword not supported: data source.

好的,这是由 EF 模型第一个连接字符串的生成方式引起的。 EF 连接字符串生成器需要构造函数中的普通连接字符串。然后首先为模型添加元数据部分。

当您创建新的连接字符串以传递给数据库上下文字符串生成器时,请更改:

public XxxDB(string connectionString): base(new EntityConnection(connectionString), true)
{ }

public XxxDB(string connectionString): base(GetEntityConnection(connectionString), true)
{ }

private static string GetEntityConnection(string connectionString)
{
    var efConnection = new EntityConnectionStringBuilder();
    efConnection.ProviderConnectionString = connectionString;
    // res://*/xxx.csdl|res://*/xxx.ssdl|res://*/xxx.msl
    var model = "xxx";
    // this is what's missing in your question
    efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model);
    return efConnection.ConnectionString;
}