如何通过Massive建立与数据库的连接?
Massive中有一个方法用于打开连接,但它接受连接字符串的名称。我想给它连接字符串。我怎么能这样做?
答案 0 :(得分:2)
在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;
}