2013-04-05 131 views
1

試圖更改我的SQL語句以更改創建用戶名的格式。我正在創建虛擬數據以便在網頁上進行測試,所以我只需要多個用戶。我想爲用戶更改名稱目前是student{integer}@email.com,我想改名字student{integer}sqlexception無法插入重複密鑰行

錯誤

SqlException: Cannot insert duplicate key row in object 'dbo.Users' with unique index 'UX_Users'. The duplicate key value is (1, [email protected]). The statement has been terminated.

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進行測試。

+0

如何定義''UX_Users''指數? – 2013-04-05 03:20:01

回答

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

} 

您只需將您提交更改你的循環內

問候

+0

我仍然收到相同的錯誤。我運行這個語句,然後運行後,我添加了'string sName ....',然後再次嘗試運行。我需要放下桌子並運行它嗎? – Masriyah 2013-04-05 03:24:10

+0

yup也許記錄已經存在於你的桌子上。你在使用SQL Server嗎? – BizApps 2013-04-05 03:25:56

+0

我可以使用它 - 我在linqpad中測試這塊,但我可以在SQL Server管理中執行此操作 – Masriyah 2013-04-05 03:26:57