FreHu FreHu - 3 months ago 8
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; }

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


And the relevant controller:

[HttpPost]
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.";
}
else
{
parameters.AllowedGroups.Add(group);
db.SaveChanges();
}
return View(parameters);
}


What can cause this behavior?

Answer

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)
{    
    modelBuilder.Entity<TestParameters>()
        .HasMany(x => x.StudentGroup)
        .WithMany(x => x.TestParameters)
    .Map(x =>
    {
        x.ToTable("StudentGroupTestParameter")
        x.MapLeftKey("Id");
        x.MapRightKey("Code");
    });
}
Comments