使用SQLCeResultSet更新/插入表

时间:2010-07-01 21:40:29

标签: c# windows-mobile compact-framework sql-server-ce linq-to-dataset

我有一个SQL Compact Edition数据库,我定期更新(通过Web服务)。

我写入数据库的部分太长了。我目前正在使用Linq to Datasets(如this question中所示)。我有heard如果我使用SQLCeResultSet执行它会更快。

所以,鉴于我有一个这样的表:

tblClient
   +- CLIENT_ID      {Unique identifier} (Primary Key)
   +- CLIENT_NAME    {varchar (100)}
   +- CLIENT_ACTIVE  {bit}

我从我的网络服务中得到的内容如下:

class Client
{
   public Guid ClientID { get; set; }
   public String ClientName { get; set; }
   public bool Active { get; set; }
}

如何将100个Client对象导入数据库?

更新现有行并插入尚未包含在数据库中的行(由主键确定)?

任何示例代码都会很棒。我有SqlCeConnection,但没有别的。

感谢您的帮助!

1 个答案:

答案 0 :(得分:13)

它看起来像这样:

编辑插入或更新

void Foo(SqlCeConnection connection)
{
    using (var cmd = new SqlCeCommand())
    {
        cmd.CommandType = CommandType.TableDirect;
        cmd.CommandText = "MyTableName";
        cmd.Connection = connection;
        cmd.IndexName = "PrimakryKeyIndexName";

        using (var result = cmd.ExecuteResultSet(
                            ResultSetOptions.Scrollable | ResultSetOptions.Updatable))
        {
            int pkValue = 100; // set this, obviously

            if (result.Seek(DbSeekOptions.FirstEqual, pkValue))
            {
                // row exists, need to update
                result.Read();

                // set values
                result.SetInt32(0, 1);
                // etc. 

                result.Update();
            }
            else
            {
                // row doesn't exist, insert
                var record = result.CreateRecord();

                // set values
                record.SetInt32(0, 1);
                // etc. 

                result.Insert(record);
            }
        }
    }
} 
相关问题