1

试图更改我的 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 进行测试。

4

1 回答 1

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();
    }

}

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

最好的祝福

于 2013-04-05T03:20:32.597 回答