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.
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 corresponding 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 could be causing this behavior?
+3
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)
{
modelBuilder.Entity<TestParameters>()
.HasMany(x => x.StudentGroup)
.WithMany(x => x.TestParameters)
.Map(x =>
{
x.ToTable("StudentGroupTestParameter")
x.MapLeftKey("Id");
x.MapRightKey("Code");
});
}
0
source to share