ASP.net MVC 5将数据添加到多个表

时间:2014-09-26 11:08:11

标签: asp.net-mvc entity-framework razor

大家好,谢谢你们的帮助。我是ASP.net MVC和EF的新手,我正在玩一些真正的项目。我真的很感激,如果有人可以指导我如何在SQL中将数据插入到具有一对多关系的两个表中。 我有一个要求,我需要在一个行为案例中添加多个系列。

  • tblCase [case_id] [case_no]
  • tblFamily [family_id] [first_name] [last_name] [case_id]

按照在线教程后,我可以添加多个家庭,但我无法理解如何:

  1. 添加新案例 - >检索最后插入的case_id
  2. 在一个提交按钮单击中添加最后插入的case_id的所有系列。
  3. 我的观点如下:

    @model List<TestMVC.Family>
    
    @{
    ViewBag.Title = "BulkData";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <style>
    td {
       padding: 5px;
    }
    </style>
    <div style="width:700px; padding:5px; background-color:white;">
    @using (Html.BeginForm("BulkData", "Save", FormMethod.Post))
    {
       @Html.AntiForgeryToken()
       @Html.ValidationSummary(true)
    
       if (ViewBag.Message != null)
        {
           <div style="border:solid 1px green">
               @ViewBag.Message
           </div>
        }
    
        <div id="dvCase">
           <table>
               <tr>
                   <td>Case Name</td>
                   <td><input type="text" value="" /></td>
               </tr>
               <tr>
                   <td>Case No</td>
                   <td><input type="text" value="" /></td>
               </tr>
           </table>
       </div>
    
       <div><a href="#" id="addNew">Add New</a></div>
       <table id="dataTable" border="0" cellpadding="0" cellspacing="0">
           <tr>
               <th>First Name</th>
               <th>Last Name</th>
               <th>Case Id</th>
               <th></th>
           </tr>
           @if (Model != null && Model.Count > 0)
            {
               int j = 0;
               foreach (var i in Model)
                {
                   <tr style="border:1px solid black">
                       <td>@Html.TextBoxFor(a => a[j].firstName)</td>
                       <td>@Html.TextBoxFor(a => a[j].lastName)</td>
                       <td>@Html.TextBoxFor(a => a[j].case_id)</td>
                       <td>
                           @if (j > 0)
                            {
                               <a href="#" class="remove">Remove</a>
                            }
                       </td>
                   </tr>
    
    
                            j++;
                }
            }
       </table>
       <input type="submit" value="Save" />
    }
    </div>
    

    我的控制器看起来像:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace TestMVC.Controllers
    {
     public class SaveController : Controller
     {
       //
       // GET: /Save/
       public ActionResult BulkData()
        {
    Case bc = new Case {case_id=0,case_no=""};           
    // This is only for show by default one row for insert data to the database
           List<Family> ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id= 0 } };
           return View(ci);
        }
    
        [HttpPost]
        [ValidateAntiForgeryToken]
       public ActionResult BulkData(List<Family> ci)
        {
           if (ModelState.IsValid)
            {
               using (FamilyContext dc = new FamilyContext())
                {
                   var behaveCase = new Case();
                   behaveCase.case_no = "1234";
                   dc.Cases.add(behaveCase);
                   foreach (var i in ci)
                    {
                       i.Case = behaveCase;                    
                       dc.Families.Add(i);
                    }
                    dc.SaveChanges();
                    ViewBag.Message = "Data successfully saved!";
                    ModelState.Clear();
                    ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id = 0 } };
                }
            }
           return View(ci);
        }
       }
    }
    

    和我的模型定义

    namespace TestMVC
    {
     using System;
     using System.Collections.Generic;
    
    public partial class Case
    {
       public Case()
        {
           this.Families = new HashSet<Family>();
        }
    
        public int case_id { get; set; }
       public string case_no { get; set; }
    
        public virtual ICollection<Family> Families { get; set; }
    }
    }
    
    namespace TestMVC
    {
    using System;
    using System.Collections.Generic;
    
    public partial class Family
    {
       public int family_id { get; set; }
       public string firstName { get; set; }
       public string lastName { get; set; }
       public int case_id { get; set; }
    
        public virtual Case Case { get; set; }
    }
    }
    

1 个答案:

答案 0 :(得分:0)

在这里添加'i'的模型:dc.Families.Add(i);当dc.SaveChanges()调用它时,它将主键修改为“i”:

if (ModelState.IsValid)
    {
       using (FamilyContext dc = new FamilyContext())
        {
           var behaveCase = new Case();
           behaveCase.case_no = "1234";
           dc.Cases.add(behaveCase);
           dc.SaveChanges(); // Save Changes Occurred. primary key in inserted in behaveCase
           int pk = behaveCase.case_id;  // You can get primary key of your inserted row
           foreach (var i in ci)
            {
               i.Case = behaveCase;                    
               dc.Families.Add(i);
               dc.SaveChanges(); // Save Changes Occured. Primary key of i is inserted
               int pkFam = i.family_id; // You can get primary key of your inserted row
            }

            ViewBag.Message = "Data successfully saved!";
            ModelState.Clear();
            ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id = 0 } };
        }
    }