C# 实体被移动而不是添加

C# 实体被移动而不是添加,c#,asp.net,asp.net-mvc,entity-framework,C#,Asp.net,Asp.net Mvc,Entity Framework,我被这个问题难住了。我试图实现的行为是,在一次测试中,分配多组允许的学生。这是正确的,但当我尝试将同一组分配给多个测试时,它会被移动而不是添加。我认为这些图片最能说明这一点 以下是我的模型: public class TestParameters { public int Id { get; set; } [Required] public string Name { get; set; } [DefaultValue(60)] //in mi

我被这个问题难住了。我试图实现的行为是,在一次测试中,分配多组允许的学生。这是正确的,但当我尝试将同一组分配给多个测试时,它会被移动而不是添加。我认为这些图片最能说明这一点

以下是我的模型:

public class TestParameters
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [DefaultValue(60)]
    //in minutes
    //0 = no limit
    [DisplayName("Time Limit")]
    public int TimeLimit { get; set; }
    [Required]
    [DefaultValue(10)]
    [DisplayName("Number of Questions")]
    public int NumQuestions { get; set; }

    [Required]
    [DisplayName("Open From")]
    public DateTime OpenFrom { get; set; }
    [DisplayName("Open To")]
    public DateTime OpenTo { get; set; }
    [DisplayName("Allowed Groups")]
    public virtual ICollection<StudentGroup> AllowedGroups { get; set; } 
}

public class StudentGroup
{
    [Required]
    [Key]
    public string Code { get; set; }

    [Required]
    public string Name { get; set; }
    public string Description { get; set; }
}

是什么导致了这种行为?

看起来很像是你建立了一对多的关系,而不是你描述的你需要的多对多的关系

在模型创建的DbContext中需要类似的内容:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{    
    modelBuilder.Entity<TestParameters>()
        .HasMany(x => x.StudentGroup)
        .WithMany(x => x.TestParameters)
    .Map(x =>
    {
        x.ToTable("StudentGroupTestParameter")
        x.MapLeftKey("Id");
        x.MapRightKey("Code");
    });
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{    
modelBuilder.Entity()
.HasMany(x=>x.StudentGroup)
.WithMany(x=>x.TestParameters)
.Map(x=>
{
x、 ToTable(“StudentGroupTestParameter”)
x、 MapLeftKey(“Id”);
x、 MapRightKey(“代码”);
});
}

谢谢!我没有意识到我还需要一个导航属性来测试StudentGroup模型中的参数。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{    
    modelBuilder.Entity<TestParameters>()
        .HasMany(x => x.StudentGroup)
        .WithMany(x => x.TestParameters)
    .Map(x =>
    {
        x.ToTable("StudentGroupTestParameter")
        x.MapLeftKey("Id");
        x.MapRightKey("Code");
    });
}