简体   繁体   English

实体框架-重复处理

[英]Entity Framework - duplicates handling

I am using Entity Framework 6, C#, and MySQL InnoDB as our db engine. 我正在使用Entity Framework 6,C#和MySQL InnoDB作为我们的数据库引擎。

I have the following code to "insert on duplicate update" a record: 我有以下代码来“插入重复更新”记录:

public async Task AddHostIdToGroup(HostsToGroup hostToGroup)
{
    using (var context = new MaintDbContext())
    {
        HostsToGroup htg = context.HostsToGroup.SingleOrDefault(hs => hs.HostId == hostToGroup.HostId);

        if (htg != null)
        {
            htg.GroupId = hostToGroup.GroupId;
            await context.SaveChangesAsync();
        }

        else
        {
            context.HostsToGroup.Add(hostToGroup);
            await context.SaveChangesAsync();
        }
    }
}

The code itself looks fine for insert on duplicate update . 该代码本身看起来很适合insert on duplicate update

Still, on our production server I occasionally see duplicate errors . 尽管如此,在我们的生产服务器上,我偶尔还是会看到duplicate errors

My initial thought was that it's a race condition issue. 我最初的想法是这是一个种族问题。

What can I do to prevent these errors, or how should I handle them? 我该如何防止这些错误,或者应该如何处理?

Your problem is not necessarily the code but what triggers that code. 您的问题不一定是代码,而是触发该代码的原因。 Say the code is triggered by an ASP.net app button, if a user double clicks on the button then it could shoot off two simultaneous requests that results in double entity creation. 假设代码是由ASP.net应用程序按钮触发的,如果用户双击该按钮,则它可能引发两个同时请求,从而导致创建双重实体。

So either fix your front end/entry point to eliminate the double create scenario, push everything into a synchronous service/queue that will allow you to deduplicate or use Where instead of Single and handle the duplication in code. 因此,要么修复前端/入口点以消除重复创建的情况,要么将所有内容推送到允许您进行重复数据删除的同步服务/队列中,或者使用Where而不是Single并处理代码中的重复数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM