读书人

linq中如何解决这个有关问题:Cannot a

发布时间: 2011-12-31 23:50:30 作者: rapoo

linq中怎么解决这个问题:Cannot add an entity with a key that is already in use.
错误信息:Cannot add an entity with a key that is already in use.
错误源:App_Web_vvfzwtzj
堆栈跟踪: 在 UserManagerUC.imgBtnSubmit_Click(Object sender, ImageClickEventArgs e) 位置 d:\MyWork\IM\Controls\UserManagerUC.ascx.cs:行号 361


C# code


protected void imgBtnSubmit_Click(object sender, ImageClickEventArgs e)

{

this.DoInit();

try

{

DBIMDataContext IM = (DBIMDataContext)Application["IM"];



try

{

var users = from user in IM.Users

where user.userID == this.txtUserID.Text

select user;



if (users.Count<User>()>0)

{

this.lblFailed.Text = "This user has been existed!";

this.lblFailed.Visible = true;

return;

}

if (string.IsNullOrEmpty(this.txtAddress.Text))

{

this.lblFailed.Visible = true;

this.lblFailed.Text = "Address is empty!";

}

else if (string.IsNullOrEmpty(this.txtCompany.Text))

{

this.lblFailed.Visible = true;

this.lblFailed.Text = "Company is empty!";

}

else if (string.IsNullOrEmpty(this.txtEmail.Text))

{

this.lblFailed.Visible = true;

this.lblFailed.Text = "Email is empty!";

}

else if (string.IsNullOrEmpty(this.txtPassword.Text))

{

this.lblFailed.Visible = true;

this.lblFailed.Text = "Password is empty!";

}

else if (string.IsNullOrEmpty(this.txtTelphone.Text))

{

this.lblFailed.Visible = true;

this.lblFailed.Text = "Telphone is empty!";

}

else

{

User xUser = new User();

xUser.userID = this.txtUserID.Text;

xUser.address = this.txtAddress.Text;

xUser.company = this.txtCompany.Text;

xUser.email = this.txtEmail.Text;

if (string.IsNullOrEmpty(this.txtNickName.Text))

{

xUser.nickName = this.txtUserID.Text;

}

else

{

xUser.nickName = this.txtNickName.Text;

}

xUser.orderFlag = int.Parse(this.ddlOrderFlag.SelectedValue);

xUser.password = this.txtPassword.Text;



xUser.roleID = this.rblRoles.SelectedValue;

xUser.telphone = this.txtTelphone.Text;



IM.Users.InsertOnSubmit(xUser);

IM.SubmitChanges();



this.divList.Visible = true;

this.BindGVUsers();

}

}

catch (Exception exception)

{

throw exception;

}

}

catch (Exception exception)

{

try

{

//发送错误信息给管理员

MyMail mail = new MyMail();

mail.Send(exception);



this.lblFailed.Visible = true;

this.lblFailed.Text = exception.Message;

}

catch (Exception ex)

{

this.lblFailed.Visible = true;

this.lblFailed.Text = ex.Message;

}

}



}


[解决办法]
xUser.userID = this.txtUserID.Text;

userID 是主键吧?应该是两次输入的txtUserID.Text重复了

[解决办法]
if (string.IsNullOrEmpty(this.txtNickName.Text))

{

xUser.nickName = this.txtUserID.Text;

}

else

{

xUser.nickName = this.txtNickName.Text;

}
这里存在问题,二次赋值。
你可以用一个临时变量来过渡
试试
string temp=xUser.nickName = this.txtNickName.Text;
if (string.IsNullOrEmpty(this.txtNickName.Text)) {temp=this.txtUserID.Text; }
xUser.nickName = temp;
[解决办法]

C# code
string temp= string.IsNullOrEmpty(this.txtNickName.Text)?this.txtUserID.Text:this.txtNickName.Text;xUser.nickName = temp; 

读书人网 >.NET

热点推荐