0

我对 EF 4.1 很陌生。我在 EF 4.1 中的 Code First 开发中遇到错误。

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

我在互联网上搜索并了解了abt的用法

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

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

4

2 回答 2

1

您正在尝试将新行插入到具有自动增量 PK 的表中,当您尝试将其添加到数据库时,您不应该在此处设置 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 回答