none
How to insert data to multiple entity in same time RRS feed

  • Question


  • I need to make multiple insert to multiple table have relation with each other

      all  id in all table is identity and already do model relation  to it

    in visual studio 2015

    what i need actually when user click submit

    Save the following data

    Name,Email,Salary,DistrictId in table Employee

    EmployeeId,CourseId in table EmployeeCourse

    EmployeeId,LanaguageId,LevelId in table EmployeeLangage

    what i write in create function in empcourse controller

    my custom model as following

    public class Customemployee { public string Name { get; set; } public string Salary { get; set; } public string Email { get; set; } public int DistrictId { get; set; } public List<Empcourse> Courses { get; set; } public List<Emplangauge> Langs { get; set; } } public class Empcourse { public int Id { get; set; } public int EmployeeId { get; set; } public int CourseId { get; set; } } public class Emplangauge { public int Id { get; set; } public int LevelId { get; set; } public int LanguageId { get; set; } } }

    my controller empcourse is

     public class empcourseController : Controller
        {
            mycourseEntities db = new mycourseEntities();
            // GET: empcourse
            public ActionResult Index()
            {
                return View();
            }
            public ActionResult Create()
            {
                ViewBag.CountryId = new SelectList(db.Countries.ToList(), "Id", "CountryName");
                ViewBag.LanaguageId = new SelectList(db.Languages.ToList(), "Id", "LnaguageName");
                ViewBag.LevelId = new SelectList(db.Levels.ToList(), "Id", "LevelName");
                ViewBag.CourseId = new SelectList(db.Courses.ToList(), "Id", "CourseName");
                return View();
            }
            [HttpPost]
            public ActionResult Create(Customemployee cemp)
            {
                return View();
            }
            public JsonResult getcitybyid(int id)
            {
                db.Configuration.ProxyCreationEnabled = false;
                return Json(db.Cities.Where(a => a.CountryId == id), JsonRequestBehavior.AllowGet);
            }
            public JsonResult getdistrictbyid(int id)
            {
                db.Configuration.ProxyCreationEnabled = false;
                return Json(db.Destricts.Where(a => a.CityId == id), JsonRequestBehavior.AllowGet);
            }
        }
    }

    my Create view is

    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Create</title>
        <script src="~/scripts/jquery-1.10.2.js"></script>
        <script>
            $(function () {
                $("#CountryId").change(function () {
                    $("#citylist").empty();
                 //  alert("error");
                    var x = $(this).val();
                    $.ajax({
                        url: "/empcourse/getcitybyid",
                        data: { id: x },
                        success:function(res)
                        {
                            $.each(res, function (i, e) {
                                $("#citylist").append("<option value='" + e.Id + "'>" + e.CityName + "<option>")
    
                            });
                        }
                    });
    
    
                });
                $("#citylist").change(function () {
                    $("#districtlist").empty();
                    // alert("error");
                    var y = $(this).val();
                    $.ajax({
                        url: "/empcourse/getdistrictbyid",
                        data: { id: y },
                        success: function (res) {
                            $.each(res, function (i, e) {
                                $("#districtlist").append("<option value='" + e.Id + "'>" + e.DistrictName + "<option>")
    
                            });
                        }
                    });
    
    
                });
                $("#CourseId").change(function () {
                    var index = 0;
                    var id = $(this).val();
                    var txt = $("#CourseId option:selected").text();
                    $("#tb").append("<tr><td><input type = 'hidden' name='Courses[" + index + "].CourseId' value='" + id + "'/></td><td>" + txt + "</td><td><input type='button' value='remove' class='r'</td></tr>")
    
                    index++;
                });
                $("#tb").on("click", ".r", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
                $("#LanaguageId").change(function () {
                    var index1 = 0;
                    var id1 = $(this).val();
                    var txt1 = $("#LanaguageId option:selected").text();
                    $("#tb1").append("<tr><td><input type = 'hidden' name='Langs[" + index1 + "].LanguageId' value='" + id1 + "'/></td><td>" + txt1 + "</td><td><input type='button' value='remove' class='s'</td></tr>")
    
                    index1++;
                });
                $("#tb1").on("click", ".s", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
    
                $("#LevelId").change(function () {
                    var index2 = 0;
                    var id2 = $(this).val();
                    var txt2 = $("#LevelId option:selected").text();
                    $("#tb2").append("<tr><td><input type = 'hidden' name='Langs[" + index2 + "].LevelId' value='" + id2 + "'/></td><td>" + txt2 + "</td><td><input type='button' value='remove' class='y'</td></tr>")
    
                    index2++;
                });
                $("#tb2").on("click", ".y", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
            });
        </script>
    </head>
    <body>
        <div>
            @using (Html.BeginForm())
            {
                <div>
                    Name:@Html.TextBoxFor(a=>a.Name)
                    <br />
                    Salary:@Html.TextBoxFor(a => a.Salary)
                    <br />
                    Email:@Html.TextBoxFor(a => a.Email)
                    <br />
                    Country:@Html.DropDownList("CountryId")
                    <br />
                    City:<select id="citylist" name="CityId"></select>
                    <br />
                    District:<select id="districtlist" name="DistrictId"></select>
                    <br />
                    Courses:@Html.DropDownList("CourseId")
                    <br />
                    <br />
                   
                    <table id="tb"></table>
                    <br />
                    <br />
                    
                    Language:@Html.DropDownList("LanaguageId")
                    <br />
                    <br />
                   
                    <table id="tb1"></table>
                    <br />
                    <br />
                   
                    Level:@Html.DropDownList("LevelId")
                    <br />
                    <br />
                    
                    <table id="tb2"></table>
                    <br />
                    <input type="submit" />
                </div>
            }
        </div>
    </body>
    </html>

    my interface and Relation diagram is 

    Saturday, August 20, 2016 7:07 PM

Answers

  • Hi eng-ahmed-salah,

    According to your code snippet, it seems that it is multiple one-to-many relationship. and I create a demo as below for your reference.

    #View

    @model MVCDemo.Models.Employee
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Create</title>
        <script src="~/Scripts/jquery-1.10.2.js"></script>
        <script>
            $(function () {
                $("#CountryId").change(function () {
                    $("#citylist").empty();
                    //  alert("error");
                    var x = $(this).val();
                    $.ajax({
                        url: "/Employees/getcitybyid",
                        data: { id: x },
                        success: function (res) {
                            $.each(res, function (i, e) {
                                $("#citylist").append("<option value='" + e.Id + "'>" + e.CityName + "</option>")
    
                            });
                        }
                    });
                });
                $("#citylist").change(function () {
                    $("#districtlist").empty();
                    // alert("error");
                    var y = $(this).val();
                    $.ajax({
                        url: "/Employees/getdistrictbyid",
                        data: { id: y },
                        success: function (res) {
                            $.each(res, function (i, e) {
                                $("#districtlist").append("<option value='" + e.Id + "'>" + e.DistrictName + "</option>")
    
                            });
                        }
                    });
                });
    
                $("#CourseId").change(function () {
                    //var index = 0;
                    var id = $(this).val();
                    var txt = $("#CourseId option:selected").text();
                    $("#tb").append("<tr><td><input type = 'hidden' name='Courses' value='" + id + "'/></td><td>" + txt + "</td><td><input type='button' value='remove' class='r'</td></tr>")
                    //index++;
                });
    
                $("#tb").on("click", ".r", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
    
                $("#LanaguageId").change(function () {
                    //var index1 = 0;
                    var id1 = $(this).val();
                    var txt1 = $("#LanaguageId option:selected").text();
                    $("#tb1").append("<tr><td><input type = 'hidden' name='Langs' value='" + id1 + "'/></td><td>" + txt1 + "</td><td><input type='button' value='remove' class='s'</td></tr>")
                    //index1++;
                });
    
                $("#tb1").on("click", ".s", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
    
                $("#LevelId").change(function () {
                    //var index2 = 0;
                    var id2 = $(this).val();
                    var txt2 = $("#LevelId option:selected").text();
                    $("#tb2").append("<tr><td><input type = 'hidden' name='Levels' value='" + id2 + "'/></td><td>" + txt2 + "</td><td><input type='button' value='remove' class='y'</td></tr>")
                    //index2++;
                });
    
                $("#tb2").on("click", ".y", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
            });
    
        </script>
    </head>
    <body>
        <div>
           @using (Html.BeginForm())
           {
            <div>
                Name:@Html.TextBoxFor(a => a.Name)
                <br />
                Salary:@Html.TextBoxFor(a => a.Salary)
                <br />
                Email:@Html.TextBoxFor(a => a.Email)
                <br />
                Country:@Html.DropDownList("CountryId")
                <br />
                City:<select id="citylist" name="CityId"></select>
                <br />
                District:<select id="districtlist" name="DistrictId"></select>
                <br />
                Courses:@Html.DropDownList("CourseId")
                <br />
                <br />
                <table id="tb"></table>
                <br />
                <br />
                Language:@Html.DropDownList("LanaguageId")
                <br />
                <br />
                <table id="tb1"></table>
                <br />
                <br />
                Level:@Html.DropDownList("LevelId")
                <br />
                <br />
                <table id="tb2"></table>
                <br />
                <input type="submit" />
            </div>
           }
        </div>
    </body>
    </html>

    #Controller

    [HttpPost] public ActionResult Create(FormCollection form) { Employee emp = new Employee(); emp.Name = form["Name"].ToString(); emp.Salary = form["Salary"].ToString(); emp.Email = form["Email"].ToString(); emp.DistrictId = Convert.ToInt32(form["DistrictId"]); var coursesId = form["Courses"]; string[] coursesIds = null; if (coursesId != null) { coursesIds = coursesId.Split(','); } List<Empcourse> courses = new List<Empcourse>(); foreach(var item in coursesIds) { Empcourse ecour = new Empcourse(); ecour.EmployeeId = emp.Id; ecour.CourseId = Convert.ToInt32(item); courses.Add(ecour); } emp.Empcourses = courses;

    //....

    //please handle language code same as courses

    db.Employees.Add(emp); db.SaveChanges(); return View(); }


    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, August 22, 2016 2:59 AM
    Moderator

All replies

  • can you help me

    what i need actually insert

    Save the following data

    Name,Email,Salary,DistrictId in table Employee

    EmployeeId,CourseId in table EmployeeCourse

    EmployeeId,LanaguageId,LevelId in table EmployeeLangage

    and write it in Create

    http post

    [HttpPost]
            public ActionResult Create(Customemployee cemp)
            {
                return View();
            }

    Sunday, August 21, 2016 3:04 PM
  • any one can help me 

    i need only what i write in create http post


    Sunday, August 21, 2016 8:52 PM
  • Hi eng-ahmed-salah,

    According to your code snippet, it seems that it is multiple one-to-many relationship. and I create a demo as below for your reference.

    #View

    @model MVCDemo.Models.Employee
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Create</title>
        <script src="~/Scripts/jquery-1.10.2.js"></script>
        <script>
            $(function () {
                $("#CountryId").change(function () {
                    $("#citylist").empty();
                    //  alert("error");
                    var x = $(this).val();
                    $.ajax({
                        url: "/Employees/getcitybyid",
                        data: { id: x },
                        success: function (res) {
                            $.each(res, function (i, e) {
                                $("#citylist").append("<option value='" + e.Id + "'>" + e.CityName + "</option>")
    
                            });
                        }
                    });
                });
                $("#citylist").change(function () {
                    $("#districtlist").empty();
                    // alert("error");
                    var y = $(this).val();
                    $.ajax({
                        url: "/Employees/getdistrictbyid",
                        data: { id: y },
                        success: function (res) {
                            $.each(res, function (i, e) {
                                $("#districtlist").append("<option value='" + e.Id + "'>" + e.DistrictName + "</option>")
    
                            });
                        }
                    });
                });
    
                $("#CourseId").change(function () {
                    //var index = 0;
                    var id = $(this).val();
                    var txt = $("#CourseId option:selected").text();
                    $("#tb").append("<tr><td><input type = 'hidden' name='Courses' value='" + id + "'/></td><td>" + txt + "</td><td><input type='button' value='remove' class='r'</td></tr>")
                    //index++;
                });
    
                $("#tb").on("click", ".r", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
    
                $("#LanaguageId").change(function () {
                    //var index1 = 0;
                    var id1 = $(this).val();
                    var txt1 = $("#LanaguageId option:selected").text();
                    $("#tb1").append("<tr><td><input type = 'hidden' name='Langs' value='" + id1 + "'/></td><td>" + txt1 + "</td><td><input type='button' value='remove' class='s'</td></tr>")
                    //index1++;
                });
    
                $("#tb1").on("click", ".s", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
    
                $("#LevelId").change(function () {
                    //var index2 = 0;
                    var id2 = $(this).val();
                    var txt2 = $("#LevelId option:selected").text();
                    $("#tb2").append("<tr><td><input type = 'hidden' name='Levels' value='" + id2 + "'/></td><td>" + txt2 + "</td><td><input type='button' value='remove' class='y'</td></tr>")
                    //index2++;
                });
    
                $("#tb2").on("click", ".y", function () {
                    $(this).parent().parent().hide();
                    $(this).parent().prev().prev().find("input").val("0");
                });
            });
    
        </script>
    </head>
    <body>
        <div>
           @using (Html.BeginForm())
           {
            <div>
                Name:@Html.TextBoxFor(a => a.Name)
                <br />
                Salary:@Html.TextBoxFor(a => a.Salary)
                <br />
                Email:@Html.TextBoxFor(a => a.Email)
                <br />
                Country:@Html.DropDownList("CountryId")
                <br />
                City:<select id="citylist" name="CityId"></select>
                <br />
                District:<select id="districtlist" name="DistrictId"></select>
                <br />
                Courses:@Html.DropDownList("CourseId")
                <br />
                <br />
                <table id="tb"></table>
                <br />
                <br />
                Language:@Html.DropDownList("LanaguageId")
                <br />
                <br />
                <table id="tb1"></table>
                <br />
                <br />
                Level:@Html.DropDownList("LevelId")
                <br />
                <br />
                <table id="tb2"></table>
                <br />
                <input type="submit" />
            </div>
           }
        </div>
    </body>
    </html>

    #Controller

    [HttpPost] public ActionResult Create(FormCollection form) { Employee emp = new Employee(); emp.Name = form["Name"].ToString(); emp.Salary = form["Salary"].ToString(); emp.Email = form["Email"].ToString(); emp.DistrictId = Convert.ToInt32(form["DistrictId"]); var coursesId = form["Courses"]; string[] coursesIds = null; if (coursesId != null) { coursesIds = coursesId.Split(','); } List<Empcourse> courses = new List<Empcourse>(); foreach(var item in coursesIds) { Empcourse ecour = new Empcourse(); ecour.EmployeeId = emp.Id; ecour.CourseId = Convert.ToInt32(item); courses.Add(ecour); } emp.Empcourses = courses;

    //....

    //please handle language code same as courses

    db.Employees.Add(emp); db.SaveChanges(); return View(); }


    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, August 22, 2016 2:59 AM
    Moderator
  • thank you for reply

    in this line it not accept

     it have wrong can you modify this line 

    emp.Empcourses = courses;

    if possible

    Monday, August 22, 2016 9:02 AM
  • emp.EmployeeCourses=courses

    how to assign list to object

    Monday, August 22, 2016 9:32 AM
  • can any one help me
    Monday, August 22, 2016 11:12 PM
  • Hi eng-ahmed-salah,

    cole wu gave you an example of how you would perform this. It errors because we do not have access to your exact class type for "Course".

    With this example below, all you need to do is replace "Empcourse" with your class type that your EF employee object is accepting. You will then wire up the appropriate "Course" properties if needed, then reassign that collection with the correct type back to the corresponding property in your Employee class.

    List<Empcourse> courses = new List<Empcourse>();
    
    foreach(var item in coursesIds)
    {
       Empcourse ecour = new Empcourse();
       ecour.EmployeeId = emp.Id;
       ecour.CourseId = Convert.ToInt32(item);
       courses.Add(ecour);
    }
    emp.Empcourses = courses;


    Best of luck.


    • Edited by DPCodesalot Tuesday, August 23, 2016 12:04 PM
    Tuesday, August 23, 2016 12:03 PM
  • all code is true

    but

    Empcourse not show when i write emp.

    when i write emp. the object EmployeeCourse Found in database only show

    but

    Empcourses not show
    Tuesday, August 23, 2016 12:26 PM
  • i attached my image to see 

    Tuesday, August 23, 2016 12:31 PM
  • and my model class customemployee

    public class Customemployee
        {
            public string Name { get; set; }
            public int Salary { get; set; }
            public string Email { get; set; }
            public int DistrictId { get; set; }
            public List<Empcourse> Courses { get; set; }
            public List<Emplangauge> Langs { get; set; }
        }
        public class Empcourse
        {
            public int Id { get; set; }
            public int EmployeeId { get; set; }
            public int CourseId { get; set; }
        }
        public class Emplangauge
        {
            public int Id { get; set; }

            public int LevelId { get; set; }
            public int LanguageId { get; set; }

        }

    }

    Tuesday, August 23, 2016 12:37 PM
  • Hi eng-ahmed-salah,

    Please try the following code.

    emp.Courses = courses;

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, August 25, 2016 2:55 AM
    Moderator
  • when i try this 

    emp.Courses = courses;

    Courses not show

    because it not have direct relation with course  table

    Thursday, August 25, 2016 5:39 AM
  • Hi eng-ahmed-salah,

    Could your please provide a simple demo about this issue via OneDrive, we'll reproduce your issue on our side and try to find a solution to resolve it.

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, August 29, 2016 6:27 AM
    Moderator
  • Why do you have DB logic in the Controller, and why are you not using Web API and a DAL that the View itself can call upon for DB access via JavaScript.
    Monday, August 29, 2016 10:39 AM