那是我在我的 Web 应用程序中使用的数据库模型, 现在我要做的就是添加新管理员或选择所有管理员,但我得到一个错误。
An item with the same key has already been added.
我用来选择所有管理员的代码:
MyContext.Administrators.Where(a => a.IsActive ==true).ToList();
我添加新管理员的代码:
Administrators AdministratorsObj = new Administrators();
AdministratorsObj.AdminFName = txtAdminFname.Text;
AdministratorsObj.AdminLName = txtLastName.Text;
AdministratorsObj.AdminLogInName = txtUserName.Text;
AdministratorsObj.AdminPassword = txtPassword.Text;
AdministratorsObj.AdminEmail = txtEmail.Text;
AdministratorsObj.AdminHomePhone = txtPhone.Text;
AdministratorsObj.AdminCellPhone = txtMobile.Text;
AdministratorsObj.AdminType = chkIsSuperAdmin.Checked;
AdministratorsObj.IsActive = chkIsActive.Checked;
AdministratorsDALObj = new AdministratorsDAL();
int AdminId = MyContext.AddAdministrators(AdministratorsObj);
AddAdministrators 方法代码:
public int AddAdministrators(Administrators AdministratorsEnt)
{
try
{
if (AdministratorsEnt == null)
return -1;
AdministratorsEnt.CreationDate = DateTime.Now;
AdministratorsEnt.DeleteStatusCode = false;
MyContext.AddToAdministrators(AdministratorsEnt);
if (MyContext.SaveChanges() > 0)
return AdministratorsEnt.AdminId;
return -1;
}
catch (Exception)
{
return -1;
}
}
请注意,管理员表中的 AdminId 列是 Identity,因此 AdminId 会自动递增。
谢谢你的帮助。