[英]How to create a DbCommand that is compatible with SQL Server and SQLite without a large condition?
HI可以说我有C#代码
private const string INSERT = "INSERT INTO Person VALUES (@FirstName, @LastName)";
public static DbCommand INSERTCOMMAND(IPerson person)
{
DbCommand command = null;
var sqlParams = new List<DbParameter>();
if(SQLManagerFactory.SQLManager is SQLServerManager)
{
command = new SqlCommand(INSERT);
sqlParams.Add(new SqlParameter("@FirstName", person.FirstName);
sqlParams.Add(new SqlParameter("@LastName", person.LastName);
}
else // SQLiteManager
{
command = new SQLiteCommand(INSERT);
sqlParams.Add(new SQLiteParameter("@FirstName", person.FirstName);
sqlParams.Add(new SQLiteParameter("@LastName", person.LastName);
}
command.Parameters.AddRange(sqlParams.ToArray());
return command;
}
哪个工作正常。 当然,在我的生产代码中,它更大并且具有更多的位置,可以对不同的命令执行类似的操作。
我的问题是,有什么办法可以缩短时间? 我不希望复制和粘贴实质上执行相同操作的代码,只是调用不同的构造函数。
提前非常感谢您。
这样的事情就可以了,我省略了细节,但是您可以弄清楚:
private const string INSERT = "INSERT INTO Person VALUES (@FirstName, @LastName)";
public static DbCommand INSERTCOMMAND(IPerson person)
{
DbCommand command = null;
var sqlParams = new List<DbParameter>();
MySqlEnum sqlType = SQLManagerFactory.SQLManager is SQLServerManager ? MySqlEnum.SQLServer : MySqlEnum.sqlLite
if(sqlType == MySqlEnum.SQLServer)
command = new SqlCommand(INSERT);
else // SQLiteManager
command = new SQLiteCommand(INSERT);
sqlParams.Add(new CustomSqlParameter(sqlType ,"@FirstName", person.FirstName);
sqlParams.Add(new CustomSqlParameter(sqlType ,"@LastName", person.LastName);
command.Parameters.AddRange(sqlParams.ToArray());
return command;
}
CustomSqlParameter的代码应该很明显
在设计和可测试性方面,我认为不适合像您的示例中那样进行耦合。
想象一下,仅对一个数据库进行了更改,并且您需要更改INSERT查询,这将导致问题,因为同一查询用于其他数据库。
实际上,您可以创建PersonRepository
抽象:
public interface IPersonRepository
{
void Add(IPerson person)
}
并创建该接口的两个实现:
public SqlServerPersonRepository : IPersonRepository
{
void Add(IPerson person)
{
//sql server specific code
}
}
public SqlLitePersonRepository : IPersonRepository
{
void Add(IPerson person)
{
//sqlite specific code
}
}
将特定于数据库的知识移到SQLManager
类中(或创建包装它的您自己的类):
public static DbCommand INSERTCOMMAND(IPerson person)
{
var sqlParams = new List<DbParameter>();
var sql = SQLManagerFactory.SQLManager; // or MyOwnSQLManager
var command = sql.CreateCommand(INSERT);
sqlParams.Add(sql.CreateParameter("@FirstName", person.FirstName));
sqlParams.Add(sql.CreateParameter("@LastName", person.LastName));
command.Parameters.AddRange(sqlParams.ToArray());
return command;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.