将 C# 对象数组与数据库表同步 [英] Synchronize C# Object Array with Database Table

查看:41
本文介绍了将 C# 对象数组与数据库表同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个调度应用程序,我的数据库表中的每一行都是在特定时间运行的不同任务.在我的应用程序中,我提取这些信息,并将每个任务存储在一个单独的对象中,并将它们存储在一个列表中.

I am writing a Scheduling application, and each row in my Database Table is a different task to run at a certain time. In my application, I pull this information, and store each task in a separate object, and keep them stored in a List.

截至目前,当我运行我的函数来刷新它时,没有检查,它只是再次添加它们.我需要找出最佳方法来查看特定作业的对象是否已经存在,如果不存在,则仅为其创建一个新对象.

As of right now, when I run my function to refresh this, there are no checks and it just adds them all again. I need to figure out the best way to see if an object already exists for the particular job, and only create a new Object for it if it doesn't.

最好的方法是检查行的 ID,然后搜索每个当前的 task 对象以查看它是否存在?我主要担心的是我不知道 Auto Increment ID 值是否替换了丢失的值.例如,如果我有 ID 为 1、2、3、4、5 的行,并且在某个时候删除了 ID 为 3 的行,添加的下一行是 3 还是 6?

Would the best way to do this be to check the ID of the row, and then search through each current task Object to see if it exists? My main concern is I do not know if the Auto Increment ID values replace missing ones. As in, if I have row's with ID 1,2,3,4,5 and at some point the row with ID 3 is removed, will the next row added be 3, or will it be 6?

推荐答案

您可以将对象存储在 Dictionary 中,其中 Key 是 int,Value 是您的对象的类型(例如 Task).然后,您可以使用键从字典中提取任务:

You could store the objects in a Dictionary where Key is int and Value is the type of your object (e.g. Task). You could then pull the task out from the Dictionary using the key:

Dictionary<int, Task> dict = new Dictionary<int, Task>();

// Code to do first-time initialise of the dictionary
....

// Subsequent refresh
Task task;
if (!dict.TryGet(id, out task))
{
    task = new Task();
    task.Id = id;
    ...
    dict.Add(id, task);
}

至于 id 的自动递增,很可能 RDBMS 将新行的值设置为最后分配的值 + 1.

As for the auto incrementing of ids, it is likely that the RDBMS sets the value for the new rows as last value assigned + 1.

这篇关于将 C# 对象数组与数据库表同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆