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

时间:2022-09-18 08:41:19

I am new to ASP.NET mvc and I have a doubt. How can I insert data into bridge table of many to many relationship table.

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

I have two models like class.cs and student.cs

我有两个模型,如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);
}

I have two tables class and student with bridge table ClassStudentTable. Using default mvc scaffolding- Create method for Student

我有两个表类和学生用桥表ClassStudentTable。使用默认的mvc scaffolding-为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");
}

Now view for create method is

现在查看create方法了

@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!");
        }
    });
});

this all the source code files I am having right now.

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

Now my question is clear.

现在我的问题很清楚了。

when I add new dynamic rows into the table for adding new class to student(shows a dropdownlist for selecting a class for student). I can select as many classes as I can for a student on front BUT HOW CAN I PASS THE VALUES TO CREATE() [HTTPPOST].

当我向表中添加新的动态行以向学生添加新类时(显示用于为学生选择课程的下拉列表)。我可以为前面的学生选择尽可能多的课程,但我如何能够创造价值()[HTTPPOST]。

can I pass through (List classs) as [parameters]?? if so how can I convert that table data into List.

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

Waiting for reply

等待回复

1 个解决方案

#1


0  

Write now you are using 1 to many relationship in your code. you should change your relationship to many to many. for achieving many to many relationship try this link

现在写,您在代码中使用1对多关系。你应该把你的关系变成很多很多。要实现多对多关系,请尝试此链接

#1


0  

Write now you are using 1 to many relationship in your code. you should change your relationship to many to many. for achieving many to many relationship try this link

现在写,您在代码中使用1对多关系。你应该把你的关系变成很多很多。要实现多对多关系,请尝试此链接