实体被移动而不是添加

时间:2015-04-27 19:38:19

标签: c# asp.net asp.net-mvc entity-framework

我对这个问题很难过。我试图实现的行为是让一个测试分配多个允许的学生组。这可以正常工作,但是当我尝试将同一组分配给多个测试时,它会被移动而不是添加。我认为这些图片解释得最好。

Step 1 - Second test has group "456" in allowed

Step 2 - I add group "456" to a different test

Step 3 - The group gets added

Step 4 - But it disappeared from the test it was in before!

以下是我的模特:

You do not have permission to call X service.

相关的控制器:

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; }
}

什么会导致这种行为?

1 个答案:

答案 0 :(得分:0)

看起来非常像你设置了一对多关系,而不是你所描述的许多关系。

你在DbContext OnModelCreating:

中需要这样的东西
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");
    });
}