简体   繁体   中英

Import Excel Data to Multiple Tables in SQL Server Database using MVC C#

I have two tables ( qf_schoolQuestion , qf_schoolOption ) qf_schoolOption table having foreign key of questionId which is primary key in qf_schoolQuestion Table.

TABLES:
qf_schoolQuestion | qf_schoolOption
----------------------------------
questionId        | schoolOptionId
questionTitle     | questionId
etc columns       | firstChoice
                  | secondChoice
                  | thirdChoice
                  | fourthChoice

I want to Bulk insert the Excel Data to Both Tables, but problem is that my code will insert the record in both tables but when data insert in qf_schoolQuestion , it will insert all data but when it insert the record in another table ie qf_schoolOption then problem occurred...

The Problem is that Suppose we have two records in excel sheet then data insert in f_schoolQuestion table is showing two records with two generated primary key, but when the data insert in another table ie qf_schoolOption table it will enter 4 records into sql server, suppose id is generated by qf_schoolQuestion table are '2044', '2045', then qf_schoolOption table will insert Both rows choice from excel sheet to '2044' Id and Both Records for '2045' ID.

HttpPost:

        public JsonResult SchoolQuesImport(HttpPostedFileBase fileUpload)
        {
            List<string> data = new List<string>();
            if (fileUpload != null)
            {
                if (fileUpload.ContentType == "application/vnd.ms-excel" || fileUpload.ContentType == "application/octet-stream" || fileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    string filename = fileUpload.FileName;
                    string targetpath = Server.MapPath("~/UploadContent/");
                    fileUpload.SaveAs(targetpath + filename);
                    string pathToExcelFile = targetpath + filename;
                    var connectionString = "";

                    if (filename.EndsWith(".xls"))
                    {
                        connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0; HDR=YES", pathToExcelFile);
                    }
                    else if (filename.EndsWith(".xlsx"))
                    {
                        connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
                    }
                    //"Xml;HDR=YES;IMEX=1\";
                    var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
                    var ds = new DataSet();

                    adapter.Fill(ds, "ExcelTable");

                    DataTable dtable = ds.Tables["ExcelTable"];

                    string sheetName = "Sheet1";

                    var excelFile = new ExcelQueryFactory(pathToExcelFile);

                    var artistAlbums = from a in excelFile.Worksheet<qf_schoolQuestion>(sheetName) select a;
                    var parentartistalbum = from b in excelFile.Worksheet<qf_schoolOption>(sheetName) select b;

                    foreach (var a in artistAlbums)
                    {
                        try
                        {
                            if (a.questionTitle != "" && a.questionLevel != "" && a.questionLang != "")
                            {
                                qf_schoolQuestion sq = new qf_schoolQuestion();

                                #region School Question
                                //sq.questionId = a.questionId;
                                sq.examTypeId = a.examTypeId;
                                sq.examCategoryId = a.examCategoryId;
                                sq.examSubCategoryId = a.examSubCategoryId;
                                sq.examSubjectId = a.examSubjectId;
                                sq.questionLang = a.questionLang;
                                sq.questionLevel = a.questionLevel;
                                sq.questionRefBook = a.questionRefBook;
                                sq.questionTitle = a.questionTitle;
                                sq.questionYear = a.questionYear;
                                sq.createdDate = DateTime.Now;
                                sq.createdBy = User.Identity.Name;

                                #endregion
                                context.qf_schoolQuestion.Add(sq);
                                context.SaveChanges();

                                foreach (var b in parentartistalbum)
                                {
                                    try
                                    {
                                        if (b.firstChoice != "")
                                        {
                                            qf_schoolOption so = new qf_schoolOption();

                                            #region School Options
                                            so.questionId = sq.questionId;
                                            so.firstChoice = b.firstChoice;
                                            so.secondChoice = b.secondChoice;
                                            so.thirdChoice = b.thirdChoice;
                                            so.fourthChoice = b.fourthChoice;

                                            #endregion
                                            context.qf_schoolOption.Add(so);
                                            context.SaveChanges();
                                        }
                                        else
                                        {
                                            data.Add("<ul>");
                                            if (b.firstChoice == "" || b.secondChoice == null) data.Add("<li>Choices are required.</li>");

                                            data.Add("</ul>");
                                            data.ToArray();
                                            return Json(data, JsonRequestBehavior.AllowGet);
                                        }
                                    }
                                    catch (DbEntityValidationException ex)
                                    {
                                        foreach (var entityValidationErrors in ex.EntityValidationErrors)
                                        {
                                            foreach (var validationError in entityValidationErrors.ValidationErrors)
                                            {
                                                Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                                            }
                                        }
                                    }
                                }

                            }

                            else
                            {
                                data.Add("<ul>");
                                if (a.questionLang == "" || a.questionLang == null) data.Add("<li>Question Language is required.</li>");

                                data.Add("</ul>");
                                data.ToArray();
                                return Json(data, JsonRequestBehavior.AllowGet);
                            }
                        }

                        catch (DbEntityValidationException ex)
                        {
                            foreach (var entityValidationErrors in ex.EntityValidationErrors)
                            {
                                foreach (var validationError in entityValidationErrors.ValidationErrors)
                                {
                                    Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                                }
                            }
                        }
                    }

                    //deleting excel file from folder  
                    if ((System.IO.File.Exists(pathToExcelFile)))
                    {
                        System.IO.File.Delete(pathToExcelFile);
                    }
                    return Json("success", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    //alert message for invalid file format  
                    data.Add("Only Excel file format is allowed");
                    data.ToArray();
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (fileUpload == null) data.Add("Please choose Excel file");
                data.ToArray();
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }

Honestly the description of the issue is not very clear, but I'll try to propose a solution: it seems to me you firstly have to insert all records in table qf_schoolQuestion and then insert all records table qf_schoolOption ; in this way you should avoid record duplication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM