How to Upload Xml File to Database in Entity Framework Database First Using C#

  • Updated date Jul 27, 2018
  • 35.1k
  • 12

In this article. I will demonstrate how to import XML data into SQL server using MVC 5 and entity framework. I volition create a XML file and upload information technology into FileUpload in project. I volition also employ jQuery datatable plugging for searching, shorting and paging.

Introduction

In this article, I will demonstrate how to import XML data into SQL server using MVC 5 and entity framework. I will create a XML file and upload it into FileUpload in project. I will besides utilise jQuery datatable plugging for searching, shorting and paging.

Pace 1

Open up SQL server 2014 and create a database table.

  1. CREATE Table [dbo].[Product](
  2.     [Id] [int ] IDENTITY(i,1) Non Zip,
  3.     [Name] [nvarchar](l) NULL,
  4.     [Cost] [decimal](18, 0) Null,
  5.     [Quantity] [int ] NULL,
  6.  CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
  7. (
  8.     [Id] ASC
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Chief]
  10. ) ON [Chief]
  11. Become

Step 2Open Visual Studio 2015, click on New Project, and create an empty web application project.

Screenshot for creating new projection i

SQL Server

After clicking on New Project, i window will appear. Select Spider web from the left panel, choose ASP.Net Web Application, give a meaningful proper noun to your project, and and so click on OK as shown in below screenshot.

Screenshot for creating new projection 2

SQL Server

After clicking on OK ane more window volition appear; choose empty, bank check on MVC checkbox and click on OK equally shown below screenshot.

Screenshot for creating new project iii

SQL Server

Afterwards clicking on OK, the project will be created with the name of MvcImportXMLData_Demo.

Step 3Add Entity Framework at present. For that, right click on Models folder, select Add, then select New Particular, then click on it.

Screenshot for adding entity framework one

SQL Server

After clicking on new detail, you will get a window; from there, select Data from the left panel and choose ADO.Internet Entity Data Model, give information technology the proper name DBModels (this name is not mandatory you lot can give any name) and click on Add.

Screenshot for adding entity framework 2

SQL Server

Subsequently you click on "Add a window", the wizard will open, choose EF Designer from database and click Next.

Screenshot for adding entity framework iii

SQL Server

Afterward clicking on Adjacent a window will announced. Choose New Connectedness. Some other window will announced, add together your server name if it is local then enter dot (.). Choose your database and click on OK.

Screenshot for adding entity framework 4

SQL Server

Connection will exist added. Save connect as you want. You can change the name of your connection beneath. Information technology volition save connection in web config and so click on Side by side.

Screenshot for adding entity framework v

SQL Server

Afterwards clicking on Next some other window volition appear cull database table proper name as shown in the below screenshot then click on Finish.

Screenshot for adding entity framework half-dozen

SQL Server

Screenshot for adding entity framework-vii

SQL Server

Entity framework will be added and respective grade gets generated under Models folder.

Screenshot for calculation entity framework 8

SQL Server

Post-obit class volition be added,

  1. namespace  MvcImportXMLData_Demo.Models
  2. {
  3. using  Organization;
  4. using  System.Collections.Generic;
  5. public  partial course  Product
  6.     {
  7. public int  Id { get; set; }
  8. public  cord Proper noun { get; set up; }
  9. public  Nullable<decimal> Price { go; ready; }
  10. public  Nullable< int > Quantity { become; fix; }
  11.     }
  12. }

Step 4

Create a class in Models Folder name it ProductMetaData.cs

Screenshot-1

SQL Server

Screenshot-2

SQL Server

Write the post-obit code

  1. using  Organization;
  2. using  System.Collections.Generic;
  3. using  System.ComponentModel.DataAnnotations;
  4. using  Arrangement.Linq;
  5. using  System.Spider web;
  6. using  System.Xml.Serialization;
  7. namespace  MvcImportXMLData_Demo.Models
  8. {
  9.     [Serializable]
  10.     [XmlRoot("product" )]
  11. public class  ProductMetaData
  12.     {
  13.         [XmlElement("id" )]
  14. public int  Id { get; prepare; }
  15.         [XmlElement("proper noun" )]
  16. public  string Proper noun { become; set; }
  17.         [XmlElement("cost" )]
  18. public  Nullable<decimal> Toll { become; set; }
  19.         [XmlElement("quantity" )]
  20. public  Nullable< int > Quantity { go; set; }
  21.     }
  22.     [MetadataType(typeof(ProductMetaData))]
  23. public  partial class  Product
  24.     {
  25.     }
  26.     }

Step fiveRight click on Controllers folder, select Add, and so choose Controller every bit shown in the below screenshot.

SQL Server

After clicking on controller a window will appear choose MVC5 Controller-Empty click on Add together.

SQL Server

After clicking on Add another window will appear with DefaultController. Change the proper noun to HomeController so click on Add together. HomeController volition be added under Controllers folder. Remember don't change the Controller suffix for all controllers, change only highlight, and instead of Default simply change Home every bit shown in the below screenshot.

SQL Server

Complete code for controller

  1. using  MvcImportXMLData_Demo.Models;
  2. using  Arrangement;
  3. using  Organization.Collections.Generic;
  4. using  Arrangement.Linq;
  5. using  System.Spider web;
  6. using  Organization.Spider web.Mvc;
  7. using  Organisation.Xml.Linq;
  8. namespace  MvcImportXMLData_Demo.Controllers
  9. {
  10. public form  HomeController : Controller
  11.     {
  12. public  ActionResult Index()
  13.         {
  14. return  View();
  15.         }
  16. public  ActionResult GetData()
  17.         {
  18. using  (DBModel db = new  DBModel())
  19.             {
  20.                 List<Product> employeeList = db.Products.ToList<Production>();
  21. return  Json( new  { data = employeeList }, JsonRequestBehavior.AllowGet);
  22.             }
  23.         }
  24.         [HttpPost]
  25. public  ActionResult Upload(HttpPostedFileBase xmlFile)
  26.         {
  27. if  (xmlFile.ContentType.Equals( "application/xml" ) || xmlFile.ContentType.Equals( "text/xml" ))
  28.             {
  29.                 var xmlPath = Server.MapPath("~/FileUpload"  + xmlFile.FileName);
  30.                 xmlFile.SaveAs(xmlPath);
  31.                 XDocument xDoc = XDocument.Load(xmlPath);
  32.                 List<Product> productList = xDoc.Descendants("product" ).Select
  33.                     (production =>new  Production
  34.                     {
  35.                         Id = Convert.ToInt32(product.Element("id" ).Value),
  36.                         Proper name = product.Element("proper name" ).Value,
  37.                         Cost = Convert.ToDecimal(production.Element("price" ).Value),
  38.                         Quantity = Catechumen.ToInt32(production.Element("quantity" ).Value)
  39.                     }).ToList();
  40. using  (DBModel db = new  DBModel())
  41.                 {
  42.                     foreach (var i in productList)
  43.                     {
  44.                         var v = db.Products.Where(a => a.Id.Equals(i.Id)).FirstOrDefault();
  45. if  (5 != null)
  46.                         {
  47.                             v.Id = i.Id;
  48.                             v.Name = i.Name;
  49.                             v.Cost = i.Price;
  50.                             v.Quantity = i.Quantity;
  51.                         }
  52. else
  53.                         {
  54.                             db.Products.Add(i);
  55.                         }
  56.                         db.SaveChanges();
  57.                     }
  58.                 }
  59.                 ViewBag.Success ="File uploaded successfully.." ;
  60.             }
  61. else
  62.             {
  63.                 ViewBag.Mistake ="Invalid file(Upload xml file only)" ;
  64.             }
  65. return  View( "Alphabetize" );
  66.         }
  67.     }
  68. }

Stride vi

Create a folder to upload file with name FileUpload.

Step 7Correct click on alphabetize activity method in controller. Add view window will announced with default index name unchecked (utilise a Layout folio), and click on Add as shown in the below screenshot. View will be added in views folder nether Abode folder with name alphabetize.

Screenshot for adding view

SQL Server

Step 8Design view with HTML, cshtml and bootstrap four classes,

Consummate index view code

  1. @{
  2.     Layout = zilch;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7.     <meta name="viewport"  content= "width=device-width"  />
  8.     <title>Alphabetize</championship>
  9.     <link href="~/Content/bootstrap.min.css"  rel= "stylesheet"  />
  10.     <script src="~/scripts/jquery-three.iii.1.min.js" ></script>
  11.     <script src="~/scripts/bootstrap.min.js" ></script>
  12.     <link href="~/Content/dataTables.bootstrap4.min.css"  rel= "stylesheet"  />
  13.     <script src="~/scripts/jquery.dataTables.min.js" ></script>
  14.     <script src="~/scripts/dataTables.bootstrap4.min.js" ></script>
  15.     <script blazon="text/javascript"  src= "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js" ></script>
  16.     <way type="text/css" >
  17.         .fault {
  18.             color: cherry;
  19.             display:inline -block;
  20.             margin-bottom: -57px !important;
  21.             width: 100%;
  22.         }
  23.     </style>
  24.     <script blazon="text/javascript" >
  25.         $(document).ready(function () {
  26.             $('grade' ).validate({
  27.                 rules: {
  28.                     xmlFile: {
  29.                         required:truthful
  30.                     }
  31.                 },
  32.                 messages: {
  33.                     xmlFile:"Choose file to upload" ,
  34.                 }
  35.             })
  36.             $('#dataTable' ).DataTable({
  37. "ajax" : {
  38. "url" : "/Habitation/GetData" ,
  39. "type" : "GET" ,
  40. "datatype" : "json"
  41.                 },
  42. "columns" : [
  43.                     {"data" : "Id"  },
  44.                     {"data" : "Proper name"  },
  45.                     {"information" : "Price"  },
  46.                     {"data" : "Quantity"  }
  47.                 ]
  48.             });
  49.         });
  50.     </script>
  51. </caput>
  52. <body>
  53.     <divgrade = "container py-5" >
  54.         @using  (Html.BeginForm( "Upload" , "Home" , FormMethod.Postal service, new  { enctype = "multipart/class-data"  }))
  55.         {
  56.             <divclass = "row" >
  57.                 <divcourse = "col-sm-1 col-md-6 col-xs-12" >
  58.                     <h5class = "text-danger" >@ViewBag.Error</h5>
  59.                     <h5class = "text-success" >@ViewBag.Success</h5>
  60.                     <divform = "form-group" >
  61.                         <label>Choose XML File:</label>
  62.                         <divclass = "input-group" >
  63.                             <divclass = "custom-file" >
  64.                                 <input id="xmlFile"  proper name= "xmlFile"  type= "file" grade = "custom-file-input"  />
  65.                                 <labelcourse = "custom-file-label" ></label>
  66.                             </div>
  67.                             <divclass = "input-grouping-append" >
  68.                                 <input type="submit" form = "btn btn-outline-primary"  value= "Upload"  />
  69.                             </div>
  70.                         </div>
  71.                     </div>
  72.                 </div>
  73.             </div>
  74.         }
  75.         <table id="dataTable" class = "table table-bordered table-striped" >
  76.             <thead>
  77.                 <tr>
  78.                     <thursday>ID</th>
  79.                     <th>Name</th>
  80.                     <thursday>Price</th>
  81.                     <th>Quantity</thursday>
  82.                 </tr>
  83.             </thead>
  84.         </table>
  85.     </div>
  86. </torso>
  87. </html>

Pace 9Create an xml file with the name products.xml

  1. <?xml version= "1.0"  encoding= "utf-8"  ?>
  2. <products>
  3.   <product>
  4.     <id>1</id>
  5.     <proper name>Mobele Telephone</name>
  6.     <cost>12000</toll>
  7.     <quantity>2</quantity>
  8.   </product>
  9.   <product>
  10.     <id>two</id>
  11.     <name>Manus Sentinel</name>
  12.     <cost>1200</price>
  13.     <quantity>v</quantity>
  14.   </product>
  15.   <product>
  16.     <id>3</id>
  17.     <proper name>T-Shirt</name>
  18.     <cost>499</price>
  19.     <quantity>2</quantity>
  20.   </product>
  21.   <product>
  22.     <id>iv</id>
  23.     <proper noun>Shoe</name>
  24.     <price>999</cost>
  25.     <quantity>2</quantity>
  26.   </production>
  27.   <production>
  28.     <id>5</id>
  29.     <name>Jeans</proper noun>
  30.     <price>999</price>
  31.     <quantity>two</quantity>
  32.   </product>
  33. </products>

Pace tenRun Projection ctrl+F5

Screenshot-1

SQL Server

Screenshot-ii

SQL Server

Screenshot-three

SQL Server

Screenshot-four

SQL Server

Screenshot-five

SQL Server

Screenshot-6

SQL Server

Determination

In this commodity I accept explained how to import xml Meta data in SQL server using MVC 5 step by step. I hope information technology volition assistance y'all in your project.

grantthalow.blogspot.com

Source: https://www.c-sharpcorner.com/article/how-to-import-xml-data-in-sql-server-using-mvc-5/

0 Response to "How to Upload Xml File to Database in Entity Framework Database First Using C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel