简体   繁体   English

空表上的System.Data.Linq.DuplicateKeyException

[英]System.Data.Linq.DuplicateKeyException on empty table

I get this error: 我收到此错误:

System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.

When I run this code, which walks a directory and puts associated records in a database. 当我运行此代码时,它会遍历目录并将相关记录放入数据库中。

   public string RefreshClientTable(string username, string companyName) {
        string company_path = @"M:/" + companyName + "/Clients/";
        string info = "";
        ExplorerBAL b = new ExplorerBAL();
        List<Explorer.DirModel> c = b.Explorer(company_path).dirModelList;
        DataContext dbContext = new BaseDataContext();
        var db_company_clients = dbContext.Clients.Where(d => d.co_name == companyName).ToList();
        foreach (var client_name in c) {
            //Determine if client exists
            info = info + "Found: " + client_name.DirName + "\n";
            int client_in_db = dbContext.Clients.Count(f => f.co_name == companyName && f.cl_name == client_name.DirName);
            if (client_in_db == 1) {
                //Update ancillary fields (later)
            }
            else {
                info = info + "Updating: " + client_name.DirName + "\n";
                //Insert the record if non-existant
                Project insert_sql = new Project() {
                    co_name = companyName,
                    cl_name = client_name.DirName
                    //Update ancillary fields (later)
                };
                dbContext.Projects.InsertOnSubmit(insert_sql);
            }
        }

        try {
            dbContext.SubmitChanges();
            return "SUCCESS:\n" + info;
        }
        catch (Exception e) {
            return "ERROR:\n" + info + e.ToString() + "\n";
        }
    }

Note that the tables are empty and the primary keys are two varchar fields. 请注意,表是空的,主键是两个varchar字段。 Based on research I suspect its some kind of an issue with the multiple calls to dbContext. 基于研究,我怀疑它对dbContext的多次调用存在某种问题。 I suspect it would work if I wasn't first checking for the existing of the item, but I really need to do that. 我怀疑如果我没有先检查项目的现有情况会有效,但我真的需要这样做。

Does any one know anything about this issue? 有没有人知道这个问题? There are similar questions, but no suitable answers... yet inserting into a table is a very common operation so something must be very specifically wrong. 有类似的问题,但没有合适的答案......但是插入表格是一个非常常见的操作,所以必须非常特别错误。

Well, I hate to solve an 8 hour long problem with a typo solution. 好吧,我讨厌使用拼写错误的解决方案解决长达8小时的问题。 But here it is: 但这里是:

dbContext.Projects.InsertOnSubmit(insert_sql);

should have been: 本来应该:

dbContext.Clients.InsertOnSubmit(insert_sql);

Copy/paste error 复制/粘贴错误

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

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