如何插入数据到多对多关系表asp.net mvc

本文关键字:关系 asp mvc net 何插入 插入 数据 | 更新日期: 2023-09-27 18:17:29

我是ASP新手。. NET mvc和我有一个疑问。如何将数据插入到多对多关系表的桥接表中?

我有两个模型像Class.cs和student.cs

public class Class
{
public int classId {get; set;}
public string classname {get; set;}
public virtual List<Student> Class {get; set;}
}
public class Student
{
public int studentId {get; set;}
public string studentname {get; set;}
public virtual List<Class> Class {get; set;}
}
//data layer
public class ClassConfiguration : EntityTypeConfiguration<Class>
{
public ClassConfiguration()
{
HasMany(c => c.Student).WithMany(c => c.Class).Map(c => {c.MapLeftKey("classId");
c.MapRightKey("studentId");
c.ToTable("ClassStudentTable");
});
}
}
//I can see ClassStudentTable in database not in entities.
//Mapping between these two
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
public DbSet<Class> Class {get; set;}
public DbSet<Student> Student {get; set;}
protected override void OnModelCreating(DbModleBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ClassConfiguration());
base.OnModelCreating(modelBuilder);
}

我有两个表类和学生桥表ClassStudentTable。使用默认的mvc脚手架-为Student创建方法

//http:get for student
public ActionResult Create()
{
ViewBag.Class = new SelectList(db.Class, "classId", "classname");
return View();
}
//http:post for student
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Bind(Include = "studentId,studentname") Student student)
{
if(ModelState.IsValid)
db.Student.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}

现在创建方法的视图是

@model TestProject.Models.Student
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-horizontal">
 <div class="form-group">
  @Html.LabelFor(model => model.studentname, htmlAttributes: new {@class = "control-label col-md-2"})
   <div class="col-md-10">
    @Html.EditorFor(model => model.studentname, new { htmlAttributes = new {@class ="form-control"}})
    @Html.ValidateMessengerFor(model => model.studentname, "", new {@class = "text-danger"})
   </div>
 </div> 
<table class="table" id="tbClass">
 <tr class="tr-header">
  <th>Class</th>
  <th><a href="javascript:void(0);" id="addMore"></th>
 </tr>
 <tr>
  <td>
   <div class="col-md-10">
    @Html.DropDownList("Class", null, htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.ValidationMessageFor(model => model.Class, "", new { @class = "text-danger" })
   </div>
  </td>
  <td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
 </tr>
</table>
<div class="form-group">
 <input type="submit" value="Create" class="btn btn-success">
 @Html.ActionLink("Cancel", "Index", null, new {@class = "btn btn-default"})
</div>
</div>
}
<script>
$(function () {
    $('#addMore').on('click', function () {
        var data = $("#tbClass tr:eq(1)").clone(true).appendTo("#tbClass");
        data.find("input").val('');
    });
    $(document).on('click', '.remove', function () {
        var trIndex = $(this).closest("tr").index();
        if (trIndex > 1) {
            $(this).closest("tr").remove();
        } else {
            alert("Sorry!! Should have atleast on row!");
        }
    });
});

这是我现在拥有的所有源代码文件。

现在我的问题很清楚了。

当我向表中添加新的动态行以向student添加新类时(显示用于为student选择类的下拉列表)。我可以选择尽可能多的类,因为我可以为学生在前面,但我怎么能传递值CREATE() [HTTPPOST]。

我可以通过(List类)作为[参数]吗??如果是这样,我如何将表数据转换为列表。

等待回复

如何插入数据到多对多关系表asp.net mvc

现在写你正在使用1到许多关系在你的代码。您应该将您的关系更改为多对多。要实现多对多关系,请尝试此链接