【问题标题】:Compare a List<T> to a database table将 List<T> 与数据库表进行比较
【发布时间】:2015-11-03 14:13:27
【问题描述】:

我正在处理一个包含 SessionID 和 EmployeeID 的对象。 基于此,我应该比较数据库表是否包含该会话的该员工。

如果表包含记录而我的对象包含,则什么也不会发生。

如果表格包含记录而我的对象不包含,则应将其从表格中删除。

如果表不包含记录而我的对象包含,则应将其添加到表中。

看起来工作很快,但我有点挣扎。

编辑:

显然,该表具有 SessionID 和 EmployeeID 列,作为我的对象的属性。

下面是实际代码:

foreach (Employee _emp in MyObj.Employees)
{
    Command.Parameters.Add(":sessionid", MyObj.SessionID);
    Command.Parameters.Add(":employeeid", _emp.EmployeeID);

    Command.CommandText = getEmployeeID;

    int employeeID;

    Int32.TryParse(Convert.ToString(Command.ExecuteScalar()), out employeeID);

    // If the employee is not in the db, add it

    if (employeeID == 0)
    {
        Command.CommandText = insertEmployee;

        [[Various Parameters]]

        Command.ExecuteNonQuery();

        Command.Parameters.Clear();
    }

    // if the employee is in the db but not in the current list, remove it from the db

    else if (employeeID != Convert.ToInt32(_emp.EmployeeID))
    {
        Command.CommandText = deleteEmployee;

        Command.ExecuteNonQuery();

        Command.Parameters.Clear();
    }
}

更新:

好的,现在我可以检查数据库中是否存在员工,并根据该插入记录。

问题是,代码永远不会进入 else if 条件,因为 MyObj.Employees 不再包含我想从数据库中删除的记录,所以

employeeID != Convert.ToInt32(_emp.EmployeeID)

结果总是错误的,因为 MyObj.Employees 中唯一的对象是我正在检查数据库中存在的对象。

【问题讨论】:

  • 到目前为止,您尝试了什么?
  • @Thomas 这是更新后的代码
  • hnote 的一件事:else if (employeeID != 0 the employeeID != 0 不需要,因为您在employeeID == 0 的else 部分。
  • 那方面:究竟是什么在那里不起作用?
  • “有点挣扎”是什么意思——有什么问题?

标签: c# mysql plsql


【解决方案1】:

我最终使用了这段代码:

Command.Parameters.Add(":sessionid", MyObj.SessionID);

// Delete all the employees for that session

Command.CommandText = DeleteEmployees;

Command.ExecuteNonQuery();

Command.Parameters.Clear();

// Insert all the current employees in the list object in the db

Command.CommandText = InsertEmployees;

foreach (Company.Employee _emp in MyObj.Employees)
{
     [[ various parameters]]

    Command.ExecuteNonQuery();

    Command.Parameters.Clear();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多