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

标签 c# asp.net asp.net-mvc entity-framework

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

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/

相关文章:

c# - DataGridComboBoxColumn 不显示 SelectedItem

c# - IIS 8 : Asp. 网络 Web 应用程序部署

c# - 在 Debug模式下构建时的 bool 值与在 Release模式下不同

javascript - Ajax成功函数未接收数据

jquery - Bootstrap Carousel 无法与 asp.net MVC 一起使用

c# - 获取 Html.AntiForgeryToken 会引发错误 "Server cannot modify cookies after HTTP headers have been sent"

c# - 如何在 WPF 列表框中禁用 Windows 声音?

c# - 将 List<Expression<Func<T, bool>>> 组合到 OR 子句 LINQ

c# - 超过100位玩家在线时套接字失败

asp.net-mvc - ASP.NET MVC 获取具有特定配置文件属性的用户列表