Object moves instead of added

I am stumped on this issue. The behavior I'm trying to achieve is one test to have multiple groups of learners allowed. This works correctly, but when I try to assign the same group for multiple tests, it will be moved rather than added. I think the photographs explain this best.

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!

Here are my models:

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

    public string Name { get; set; }

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

    [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
    public string Code { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }


And the corresponding controller:

public ActionResult NewGroup()
    var groupCode = Request["groupCode"];
    var paramId = Request["parametersId"];

    var group = db.StudentGroups.Find(groupCode);
    var parameters = db.TestParameters.Find(int.Parse(paramId));

    if (group == null)
        ViewBag.ErrorMessage = "No group with code " + groupCode + " exists.";
    else if (parameters.AllowedGroups.Contains(group))
        ViewBag.ErrorMessage = "The group with code " + groupCode + " already has access to this test.";
    return View(parameters);


What could be causing this behavior?


source to share

1 answer

It looks awful, as if you are in a one-to-many relationship rather than the many you are talking about.

You need something like this in your DbContext OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        .HasMany(x => x.StudentGroup)
        .WithMany(x => x.TestParameters)
    .Map(x =>




All Articles