在比较特定列时,防止重复插入SQL db必须使用PetaPoco

时间:2017-02-20 18:46:02

标签: c# sql petapoco

背景信息

我目前正在开发一个电子邮件抓取工具,它会在我抓取信息的电子邮件数据库中创建记录。目前我的公司已经限制我使用Petapoco进行代码维护问题。我正在运行的当前问题是重复记录被记录到数据库中。我一直在寻找可以给我提示如何实现这一目标的示例或文档,但我一直无法找到。

问题

目前我可以在没有问题的情况下将记录插入到数据库中,但它也会插入重复项。

其他信息

我试图确保唯一的列是[AppointmentUniqueId],我有一个Id的主键,我的表是AppointmentActivities,我想要插入的是一个记录的类模型。

当前代码

public static async Task<bool> InsertActivitiesData(List<Act_Appointments> recordList)
{
    int recordsInserted = 0;
    try
    {
        using (PetaPoco.Database databaseInstance = new PetaPoco.Database("PMconString"))
        {
            foreach (var record in recordList)
            {
                databaseInstance.Insert("AppointmentActivities", "Id", record);
                recordsInserted++;
            }
        }
        log4net.LogManager.GetLogger("AppInfoLogger").Info("[ ServiceRan : Insert Email Data To DB ]" + "[ Records Inserted: " + recordsInserted.ToString() + " ]");
        return true;
    }
    catch (Exception ex)
    {
        log4net.LogManager.GetLogger("AppErrorLogger").Error("[ReconcileEvents]" + JsonConvert.SerializeObject(ex));
        log4net.LogManager.GetLogger("EmailLogger").Error("[ReconcileEvents]" + JsonConvert.SerializeObject(ex));
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

我采取了最实际的方式来解决这个问题。我不确定它是否是最有效的,但由于时间的限制,我真的不能长期讨论这个问题。我继续在AppointmentUniqueId上运行一个查询,如果它返回null,则意味着该项目不存在。

    public static async Task<bool> InsertActivitiesData(List<Act_Appointments> recordList)
    {
        int recordsInserted = 0;
        int duplicates = 0;
        try
        {
            using (PetaPoco.Database databaseInstance = new PetaPoco.Database("PMconString"))
            {                   
                foreach (var record in recordList)
                {

                    if (databaseInstance.FirstOrDefault<Act_Appointments>("SELECT * FROM AppointmentActivities WHERE AppointmentUniqueId =@0", record.AppointmentUniqueId) == null)
                    {
                        databaseInstance.Insert("AppointmentActivities", "Id", record);
                        recordsInserted++;
                    }
                    else
                    {
                        duplicates++;
                    }                                            
                }
            }
            log4net.LogManager.GetLogger("AppInfoLogger").Info("[Insert Appointment Data To DB]" + "[ Records Inserted: " + recordsInserted.ToString() + " ]"+ "[ Duplicates Not Inserted: " + duplicates.ToString() + " ]");
            return true;
        }
        catch (Exception ex)
        {
            log4net.LogManager.GetLogger("AppErrorLogger").Error("[ReconcileEvents]" + JsonConvert.SerializeObject(ex));
            log4net.LogManager.GetLogger("EmailLogger").Error("[ReconcileEvents]" + JsonConvert.SerializeObject(ex));
            return false;
        }
    }

PS。

我将保持开放状态10天,以便听取社区的反馈意见,看看是否有不同的方法来解决我想要做的事情。