空表上的System.Data.Linq.DuplicateKeyException

时间:2016-12-23 03:32:25

标签: c# entity-framework linq insert

我收到此错误:

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

当我运行此代码时,它会遍历目录并将关联的记录放入数据库中。

   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";
        }
    }

请注意,表是空的,主键是两个varchar字段。基于研究,我怀疑它对dbContext的多次调用存在某种问题。我怀疑如果我不首先检查项目的现有情况会有效,但我真的需要这样做。

有没有人知道这个问题?有类似的问题,但没有合适的答案......但是插入表格是一种非常常见的操作,所以某些事情必定是非常错误的。

1 个答案:

答案 0 :(得分:0)

好吧,我讨厌用拼写错误解决方案来解决长达8小时的问题。但这是:

dbContext.Projects.InsertOnSubmit(insert_sql);

应该是:

dbContext.Clients.InsertOnSubmit(insert_sql);

复制/粘贴错误