已添加具有相同键的项目。选择所有记录时出错

时间:2012-08-25 11:10:23

标签: asp.net entity-framework

这是我在我的Web应用程序中使用的DataBase模型 enter image description here 现在我所要做的就是添加新管理员或选择所有管理员,但我收到错误。

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

请注意,administrators表中的AdminId列是Identity,因此AdminId会自动递增。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我在EF 4.1中遇到了同样的问题。与现有的应用程序。 发生了什么? EF 4.1需要.net framework 4.0。 Windows更新用4.5取代了.net framework 4.0,我得到了同样的错误。 解决方案是卸载.net 4.5并安装.net 4.0。