簡體   English   中英

如何創建沒有大條件的與SQL Server和SQLite兼容的DbCommand?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM