如何通过 Massive 连接到数据库?
Massive 中有一种方法可以打开连接,但它接受连接字符串的名称。我想给它连接字符串。我怎样才能做到这一点?
在 Open() 方法中的 Massive 代码中创建了 DynamicModel,在 DynamicModel 构造函数中我发现了这一行(Massive.cs 127 行):
ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
这意味着您需要将连接字符串存储在配置文件中,并将相应的连接字符串名称传递给 Open 方法。
您需要的是创建重载方法来接受连接字符串。这是一个例子:
public static DynamicModel Open(string connectionString, string providerName="System.Data.SqlClient")
{
dynamic dm = new DynamicModel(connectionString, providerName);
return dm;
}
public DynamicModel(string connectionString, string providerName ="System.Data.SqlClient", string tableName = "",
string primaryKeyField = "", string descriptorField = "")
{
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
DescriptorField = descriptorField;
_factory = DbProviderFactories.GetFactory(providerName);
ConnectionString = connectionString;
}