EF 4.1代码优先错误 - IDENTITY_INSERT设置为OFF

时间:2012-04-08 06:56:22

标签: database entity-framework model ef-code-first entity

我是EF 4.1的新手。我在EF 4.1中的Code First开发中遇到了错误。

“当IDENTITY_INSERT设置为OFF时,无法在表'表'中为标识列插入显式值。”

我在网上搜索并了解了

的用法
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)].

但没用。我也将选项从Identity更改为None。但没用。

2 个答案:

答案 0 :(得分:1)

您正尝试在具有自动增量PK的表中插入新行,当您尝试将其添加到数据库时,不应在此处设置ID属性。

答案 1 :(得分:0)

我遇到了同样的错误,因为我在我的类中错误地定义了一个外键关系:

public partial class Student
{
    [Key]
    public int StudentId { get; set; }

    public string StudentName { get; set; }
    public int StudentAge { get; set; }
    public int GradeNumber { get; set; }
    public string LockerNumber { get; set; }
    public string TeacherID { get; set; }
    public string StudentComments { get; set; }

    // Navigation properties
    [ForeignKey("TeacherID")]
    public virtual Teacher Teacher { get; set; }

    public virtual GradeLevel GradeLevel { get; set; }

    // the code below is incorrect, the StudentClass should have the StudentId 
    // as the FK entity:

    [ForeignKey("StudentId")]
    public virtual StudentClass StudentClass { get; set; }
}

StudentClass类

public partial class StudentClass
{
    [Key]
    public int RowId { get; set; }
    public int StudentId { get; set; }
    public int ClassSubjectId { get; set; }

    // Navigation properties
    [ForeignKey("ClassSubjectId")]
    public virtual ClassSubject ClassSubject { get; set; }

    // this is the way the relationship should be defined: 

    [ForeignKey("StudentId")]
    public virtual Student Student { get; set; }
}