插入具有一对一或一对关系的对象时出错

问题描述 投票:0回答:1

考虑课程可以有课程或不。所以课程和课程之间的关系是1..0或1..1。课程是:

public class Course
{
    public int Id {get; set;}
    public Curriculum { get; set; }
}


public class Curriculum 
{ 
    [ForeignKey("Course")]
    public int Id { get; set; }     

    public Course Course { get; set; }     
}

我通过下面的流畅api配置了关系:

public class CourseConfiguration : EntityTypeConfiguration<Course>
{
    public CourseConfiguration()
    {
        HasOptional(course => course.Curriculum)
            .WithRequired(cur => cur.Course);
    }
}

不幸的是,当我想在Db中保存一个课程时,会出现以下错误:

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

另外,我将属性[DatabaseGenerated(DatabaseGeneratedOption.Identity)][DatabaseGenerated(DatabaseGeneratedOption.None)]添加到Curriculum类的主键,但它没有效果或创建新的异常!

你有什么主意吗?

c# entity-framework insert ef-code-first entity-relationship
1个回答
0
投票

我拿了你的代码,它起作用了:

> public class MyContext : DbContext
>     {
>         public DbSet<Curriculum> Curriculum { get; set; }
>         public DbSet<Course> Course { get; set; }
> 
>         protected override void OnModelCreating(DbModelBuilder modelBuilder)
>         {
>             base.OnModelCreating(modelBuilder);
>             modelBuilder.Configurations.Add(new CourseConfiguration());
>         }
>     }
>     public class Course
>     {
>         [DatabaseGenerated(DatabaseGeneratedOption.None)]
>         public int Id { get; set; }
>         public Curriculum Curriculum { get; set; }
>     }
> 
>     public class CourseConfiguration : EntityTypeConfiguration<Course>
>     {
>         public CourseConfiguration()
>         {
>             HasOptional(course => course.Curriculum)
>                 .WithRequired(cur => cur.Course);
>         }
>     }
>     public class Curriculum
>     {
>         [ForeignKey("Course")]
>         public int Id { get; set; }
> 
>         public Course Course { get; set; }
>     }

但是,在您的情况下,由于首次创建表时身份设置为true,因此EF不会为您更改它。如果您在第一次迁移中在Course的Id属性上具有以下属性,则不会出现此问题:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

为了解决您的问题,您需要重新创建表课程。以下链接也可以帮助您:https://stackoverflow.com/a/18917348/2348125

© www.soinside.com 2019 - 2024. All rights reserved.