sqlexception无法插入重复的键行

时间:2013-04-05 03:11:31

标签: c# sql

尝试更改我的SQL语句以更改用户名创建方式的格式。我正在创建虚拟数据以便在网页上进行测试,所以我只需要多个用户。我想更改当前用户student{integer}@email.com的名称,我想将名称更改为student{integer}

错误

  

SqlException :无法在具有唯一索引“UX_Users”的对象“dbo.Users”中插入重复的键行。重复键值为(1,student0@email.com)。   声明已经终止。

SQL语句

string basestring = "student{0}@email.com";
string userName = "Student{0}";

using (Database dc = new Database())
{
    dc.Connection.Open();
    for (int i = 0; i < 400; i++)
    {
        string email = string.Format(basestring,i);
        string sName = string.Format(userName, i);
        User u = new User(){ Name = sName, UserName = email, InstitutionUniqueID = email, Email = email, CreationDate=DateTime.Now, InstitutionsID=1, GUID= Guid.NewGuid() };
        dc.Users.InsertOnSubmit(u); 
    }
    dc.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
}

这是我收到错误的地方:

dc.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);

我正在使用linqpad对此进行测试。

1 个答案:

答案 0 :(得分:1)

将您的代码更改为:

string basestring = "student{0}@email.com";
string userName = "Student{0}";

using (Database dc = new Database())
{

    for (int i = 0; i < 400; i++)
    {
         dc.Connection.Open();
        string email = string.Format(basestring,i);
        string sName = string.Format(userName, i);
        User u = new User(){ Name = sName, UserName = email, InstitutionUniqueID = email, Email = email, CreationDate=DateTime.Now, InstitutionsID=1, GUID= Guid.NewGuid() };
        dc.Users.InsertOnSubmit(u); 
        dc.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
        dc.Connection.Close();
    }

}

您只需将提交更改放在循环中

最好的问候