0

I am very new to EF 4.1. I am getting the error in my Code First development in EF 4.1.

"Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF."

I searched in internet and understood abt the usage of the

[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)].

But no use. I changed the option from Identity to None also. But no use.

4

2 に答える 2

1

自動インクリメント PK を使用してテーブルに新しい行を挿入しようとしています。DB に追加しようとするときに、ここで ID プロパティを設定しないでください。

于 2012-04-08T07:11:15.443 に答える
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; }
}
于 2012-12-22T17:52:11.947 に答える