FreHu FreHu - 1 month ago 4x
ASP.NET (C#) Question

Entity gets moved instead of added

I am stumped on this problem. The behavior I am trying to achieve is for one test to have multiple allowed groups of students assigned. This works correctly, but when I try to assign the same group to multiple tests, it gets moved instead of added. I think the pictures explain it 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 relevant 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 can cause this behavior?


It looks awfully like you have a one-many relationship set up rather than the many-many you describe you need.

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 =>