SQL Server CE不支持EF支持ExecuteSQLCommand吗?

时间:2018-08-17 19:08:16

标签: c# entity-framework tsql sql-server-ce

我一直在使用带有实体框架的SQL Server Express LocalDb和VS2015开发C#WPF项目。我已经为数据库构建了一个自定义种子机,该种子机从Excel文件中读取测试数据,将Excel数据简单地组合到命令字符串中,并使用context.Database.ExecuteSQLCommand插入。

现在,我正在考虑使用SQL Server Compact Edition 4.0启动该项目,但是我发现此命令不再起作用。我是否必须使用SqlCeConnectionSqlCeCommand重新写上载器,还是丢失了某些内容?

此外,从某个地方我了解到,使用EF可以切换SQL提供程序,并且代码不需要其他更改。我会在路上得到更多惊喜吗?

上载器命令示例:

string cmd = "INSERT INTO Venues(Name, City, Telephone) Values ('X','Y','Z')"
context.Database.ExecuteSqlCommand(cmd);

错误:

  

解析查询时出错。 [令牌行号= 2,令牌行偏移量= 1,令牌错误=插入]

这不仅仅是一个测试问题,因为我也想在生产版本中包含此上传器,以便快速插入主数据(例如员工列表)。

编辑:上传者代码。如果可以在不依靠原始SQL的情况下完成此操作,那也是一个很好的解决方案。

这将循环遍历Excel工作表(以实体命名)和列(第一行具有属性名称)和行2-> n(数据)。这可以处理Excel限制内的任何数量的数据上载。关键是代码不了解实体(可能也可以参数化DataContext)。代码可能不是最佳的,因为我只是一个初学者,但是对我有用,除非不是SQL CE。进行编辑以适合CE并不是一个大问题,但是我想问一问可能更好的方法。

public static class ExcelUploader
{
    static ArrayList data;
    static List<string> tableNames;

    public static string Upload(string filePath)
    {
        string result = "";
        data = new ArrayList();
        tableNames = new List<string>();
        ArrayList upLoadData = ReadFile(filePath);
        List<string> dataList = ArrayListToStringList(upLoadData);

        using (var db = new DataContext())
        {
            using (var trans = db.Database.BeginTransaction())
            {
                try
                {
                    foreach (var cmd in dataList)
                    {
                        Console.WriteLine(cmd);
                        db.Database.ExecuteSqlCommand(cmd);
                    }
                    db.SaveChanges();
                    trans.Commit();
                }
                catch (Exception e)
                {
                    trans.Rollback();
                    result = e.Message;
                    MessageBox.Show(result);
                }
            }
        }
        return result;
    }


    private static ArrayList ReadFile(string fileName)
    {
        List<string> commands = new List<string>();

        var xlApp = new Microsoft.Office.Interop.Excel.Application();
        var wb = xlApp.Workbooks.Open(fileName, ReadOnly: true);
        xlApp.Visible = false;
        foreach (Worksheet ws in wb.Worksheets)
        {
            var r = ws.UsedRange;
            var array = r.Value;
            data.Add(array);
            tableNames.Add(ws.Name);
        }
        wb.Close(SaveChanges: false);
        xlApp.Quit();

        return data;
    }

    private static List<string> ArrayListToStringList(ArrayList arrList)
    {
        List<string> result = new List<string>();

        for(int tableAmount = 0;tableAmount<data.Count;tableAmount++)
        {
            result.Add(ArrayToSqlCommand(arrList[tableAmount] as Array, tableNames[tableAmount]));
        }

        return result;
    }

    private static string ArrayToSqlCommand(Array arr, string tableName)
    {
        int propertyRow = 1;
        int firstDataRow = 2;
        string command = "";

        // loop rows                
        for (int rowIndex = firstDataRow; rowIndex <= arr.GetUpperBound(0); rowIndex++)
        {
            command += "INSERT INTO " + tableName + "(";

            //add column names
            for (int colIndex = 1; colIndex <= arr.GetUpperBound(1); colIndex++)
            {
                //get property name
                command += arr.GetValue(propertyRow, colIndex);

                //add comma if not last column, otherwise close bracket
                if (colIndex == arr.GetUpperBound(1))
                {
                    command += ") Values (";
                }
                else
                {
                    command += ", ";
                }
            }

            //add values
            for (int colIndex = 1; colIndex <= arr.GetUpperBound(1); colIndex++)
            {
                //get property value
                command += "'" + arr.GetValue(rowIndex, colIndex) + "'";

                //add comma if not last column, otherwise close bracket
                if (colIndex == arr.GetUpperBound(1))
                {
                    command += ");";
                }
                else
                {
                    command += ", ";
                }
            }
            command += "\n";
        }

        return command;
    }

}

2 个答案:

答案 0 :(得分:0)

有两种使用原始SQL查询的方法。

初始数据

1)Excel表

+=======+=======+===========+
| Name  | City  | Telephone |
|===========================|
| Adam  | Addr1 | 111-11-11 |
|-------|-------|-----------|
| Peter | Addr2 | 222-22-22 |
+-------+-------+-----------+

2)SQL Server CE表

CREATE TABLE Venues
(
    Id        int identity primary key,
    [Name]    nvarchar(100) null,
    City      nvarchar(100) null,
    Telephone nvarchar(100) null
);

3)从Excel获取数据

在这里,我们有兴趣从Excel工作表中获取数组。一旦得到它,我们就可以安全地关闭Excel。该代码假定文件“ Employees.xlsx”位于可执行文件旁边。

private object[,] GetExcelData()
{
    xlApp = new Excel.Application { Visible = false };
    var xlBook =
        xlApp.Workbooks.Open(System.IO.Path.Combine(
                                 Environment.CurrentDirectory,
                                 "Employees.xlsx"));
    var xlSheet = xlBook.Sheets[1] as Excel.Worksheet;

    // For process termination
    var xlHwnd = new IntPtr(xlApp.Hwnd);
    var xlProc = Process.GetProcesses()
                 .Where(p => p.MainWindowHandle == xlHwnd)
                 .First();

    // Get Excel data: it's 2-D array with lower bounds as 1.
    object[,] arr = xlSheet.Range["A1"].CurrentRegion.Value;

    // Shutdown Excel
    xlBook.Close();
    xlApp.Quit();
    xlProc.Kill();
    GC.Collect();
    GC.WaitForFullGCComplete();

    return arr;
}

现在,您可以使用一种方式来生成查询。

选项1.使用ExecuteSqlCommand

使用ExecuteSqlCommand时,建议使用参数化查询以避免错误。您可以传递显式创建的SqlCeParameter,也可以传递一个值。

private void UseExecuteSqlCommand()
{
    object[,] arr = GetExcelData();

    using (var db = new EmpContext())
    {

        db.Database.Initialize(true);

        int count = 0;
        string sql = "INSERT INTO Venues (Name, City, Telephone) " +
                     "VALUES (@name, @city, @phone);";

        // Start from 2-nd row since we need to skip header
        for (int r = 2; r <= arr.GetUpperBound(0); ++r)
        {
            db.Database.ExecuteSqlCommand(
                sql,
                new SqlCeParameter("@name", (string)arr[r, 1]),
                new SqlCeParameter("@city", (string)arr[r, 2]),
                new SqlCeParameter("@phone", (string)arr[r, 3])
            );

            ++count;
        }

        conn.Close();
        MessageBox.Show($"{count} records were saved.");
    }
}

选项2。使用DbConnection

如果您希望代码更通用,则可以创建将接受DbConnection的方法。这将允许传递SqlConnectionSqlCeConnection。但是代码变得更加冗长,因为这些类是抽象的,因此我们不能使用构造函数。

private void UseDbConnection()
{
    object[,] arr = GetExcelData();

    using (var db = new EmpContext())
    {

        db.Database.Initialize(true);

        int count = 0;
        string sql = "INSERT INTO Venues (Name, City, Telephone) " +
                     "VALUES (@name, @city, @phone);";

        DbParameter param = null;

        DbConnection conn = db.Database.Connection;
        conn.Open();

        DbCommand command = conn.CreateCommand();
        command.CommandText = sql;
        command.CommandType = CommandType.Text;

        // Create parameters

        // Name
        param = command.CreateParameter();
        param.ParameterName = "@name";
        command.Parameters.Add(param);

        // City
        param = command.CreateParameter();
        param.ParameterName = "@city";
        command.Parameters.Add(param);

        // Telephone
        param = command.CreateParameter();
        param.ParameterName = "@phone";
        command.Parameters.Add(param);

        // Start from 2-nd row since we need to skip header
        for (int r = 2; r <= arr.GetUpperBound(0); ++r)
        {
            command.Parameters["@name"].Value = (string)arr[r, 1];
            command.Parameters["@city"].Value = (string)arr[r, 2];
            command.Parameters["@phone"].Value = (string)arr[r, 3];
            command.ExecuteNonQuery();
            ++count;
        }

        conn.Close();
        MessageBox.Show($"{count} records were saved.");
    }
}

您还可以对参数使用序数位置,从而避免创建参数名称并使代码更短:

private void UseDbConnection()
{

    object[,] arr = GetExcelData();

    using (var db = new EmpContext())
    {

        db.Database.Initialize(true);

        int count = 0;
        // Take a note - use '?' as parameters
        string sql = "INSERT INTO Venues (Name, City, Telephone) " +
                     "VALUES (?, ?, ?);";

        DbConnection conn = db.Database.Connection;
        conn.Open();
        DbCommand command = conn.CreateCommand();
        command.CommandText = sql;
        command.CommandType = CommandType.Text;

        // Create parameters
        command.Parameters.Add(command.CreateParameter());
        command.Parameters.Add(command.CreateParameter());
        command.Parameters.Add(command.CreateParameter());

        for (int r = 2; r <= arr.GetUpperBound(0); ++r)
        {
            // Access parameters by position
            command.Parameters[0].Value = (string)arr[r, 1];
            command.Parameters[1].Value = (string)arr[r, 2];
            command.Parameters[2].Value = (string)arr[r, 3];
            command.ExecuteNonQuery();
            ++count;
        }

        conn.Close();
        MessageBox.Show($"{count} records were saved.");
    }
}

PS 我没有检查是否打开了基础连接,但这是个好主意。

答案 1 :(得分:0)

基于JohnyL的出色输入,我能够修改我的代码,使其可以与SQL Server Express和SQL Server CE一起使用。我将新代码作为答案,因为我也无法在代码中编写属性名称,因此我不得不进一步对其进行参数化。但这是一个简单的步骤,一旦我从JohnyL那里得到了想法。虽然不确定,是否应该将数据库写入操作包装在DbTransaction中,但这目前仍然有效。

public static class ExcelUploader
{
    static ArrayList data;
    static List<string> tableNames;
    static List<DbCommand> cmdList = new List<DbCommand>();
    static DbConnection conn;

    public static void Upload(string filePath)
    {
        data = new ArrayList();
        tableNames = new List<string>();
        //get Excel data to array list
        ArrayList upLoadData = ReadFile(filePath);

        using (var db = new DataContext())
        {
            conn = db.Database.Connection;

            //transform arraylist into a list of DbCommands
            ArrayListToCommandList(upLoadData);

            conn.Open();
            try
            {
                foreach (var cmd in cmdList)
                {
                    //Console.WriteLine(cmd.CommandText);
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                var result = e.Message;
                MessageBox.Show(result);
            }
        }

    }

    //opens Excel file and reads worksheets to arraylist
    private static ArrayList ReadFile(string fileName)
    {
        List<string> commands = new List<string>();

        var xlApp = new Microsoft.Office.Interop.Excel.Application();
        var wb = xlApp.Workbooks.Open(fileName, ReadOnly: true);
        xlApp.Visible = false;
        foreach (Worksheet ws in wb.Worksheets)
        {
            var r = ws.UsedRange;
            var array = r.Value;
            data.Add(array);
            tableNames.Add(ws.Name);
        }
        wb.Close(SaveChanges: false);
        xlApp.Quit();

        return data;
    }

    //transforms arraylist to a list of DbCommands
    private static void ArrayListToCommandList(ArrayList arrList)
    {
        List<DbCommand> result = new List<DbCommand>();

        for (int tableAmount = 0; tableAmount < data.Count; tableAmount++)
        {

            ArrayToSqlCommands(arrList[tableAmount] as Array, tableNames[tableAmount]);
        }

    }

    private static void ArrayToSqlCommands(Array arr, string tableName)
    {
        //Excel row which holds property names
        int propertyRow = 1;
        //First Excel row with values
        int firstDataRow = 2;
        string sql = "";

        DbCommand cmd = conn.CreateCommand();

        sql += "INSERT INTO " + tableName + "(";

        //add column names to command text
        for (int colIndex = 1; colIndex <= arr.GetUpperBound(1); colIndex++)
        {
            //get property name
            sql += arr.GetValue(propertyRow, colIndex);

            //add comma if not last column, otherwise close bracket
            if (colIndex == arr.GetUpperBound(1))
            {
                sql += ") Values (";
            }
            else
            {
                sql += ", ";
            }
        }

        //add value parameter names to command text
        for (int colIndex = 1; colIndex <= arr.GetUpperBound(1); colIndex++)
        {
            //get property name
            sql += "@" + arr.GetValue(propertyRow, colIndex);

            //add comma if not last column, otherwise close bracket
            if (colIndex == arr.GetUpperBound(1))
            {
                sql += ");";
            }
            else
            {
                sql += ", ";
            }
        }

        //add data elements as command parameter values
        for (int rowIndex = firstDataRow; rowIndex <= arr.GetUpperBound(0); rowIndex++)
        {
            //initialize command
            cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;

            for (int colIndex = 1; colIndex <= arr.GetUpperBound(1); colIndex++)
            {
                //set parameter values
                DbParameter param = null;
                param = cmd.CreateParameter();
                param.ParameterName = "@" + (string)arr.GetValue(propertyRow, colIndex);
                cmd.Parameters.Add(param);
                cmd.Parameters[param.ParameterName].Value = arr.GetValue(rowIndex, colIndex);
            }
            //add command to command list
            cmdList.Add(cmd);

        }

    }
}