gpt4 book ai didi

c# - 实体被移动而不是添加

转载 作者:行者123 更新时间:2023-11-30 18:25:36 25 4
gpt4 key购买 nike

我被这个问题难住了。我试图实现的行为是让一个测试分配多个允许的学生组。这工作正常,但是当我尝试将同一组分配给多个测试时,它被移动而不是添加。我认为图片最能说明问题。

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!

这是我的模型:

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

以及相关的控制者:

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

什么会导致这种行为?

最佳答案

看起来你建立的是一对多关系,而不是你描述的你需要的多对多关系。

您在 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");
});
}

关于c# - 实体被移动而不是添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com