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.
- CREATE Table [dbo].[Product](
- [Id] [int ] IDENTITY(i,1) Non Zip,
- [Name] [nvarchar](l) NULL,
- [Cost] [decimal](18, 0) Null,
- [Quantity] [int ] NULL,
- CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Chief]
- ) ON [Chief]
- Become
Step 2Open Visual Studio 2015, click on New Project, and create an empty web application project.
Screenshot for creating new projection i
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
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
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
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
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
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
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
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
Screenshot for adding entity framework-vii
Entity framework will be added and respective grade gets generated under Models folder.
Screenshot for calculation entity framework 8
Post-obit class volition be added,
- namespace MvcImportXMLData_Demo.Models
- {
- using Organization;
- using System.Collections.Generic;
- public partial course Product
- {
- public int Id { get; set; }
- public cord Proper noun { get; set up; }
- public Nullable<decimal> Price { go; ready; }
- public Nullable< int > Quantity { become; fix; }
- }
- }
Step 4
Create a class in Models Folder name it ProductMetaData.cs
Screenshot-1
Screenshot-2
Write the post-obit code
- using Organization;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using Arrangement.Linq;
- using System.Spider web;
- using System.Xml.Serialization;
- namespace MvcImportXMLData_Demo.Models
- {
- [Serializable]
- [XmlRoot("product" )]
- public class ProductMetaData
- {
- [XmlElement("id" )]
- public int Id { get; prepare; }
- [XmlElement("proper noun" )]
- public string Proper noun { become; set; }
- [XmlElement("cost" )]
- public Nullable<decimal> Toll { become; set; }
- [XmlElement("quantity" )]
- public Nullable< int > Quantity { go; set; }
- }
- [MetadataType(typeof(ProductMetaData))]
- public partial class Product
- {
- }
- }
Step fiveRight click on Controllers folder, select Add, and so choose Controller every bit shown in the below screenshot.
After clicking on controller a window will appear choose MVC5 Controller-Empty click on Add together.
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.
Complete code for controller
- using MvcImportXMLData_Demo.Models;
- using Arrangement;
- using Organization.Collections.Generic;
- using Arrangement.Linq;
- using System.Spider web;
- using Organization.Spider web.Mvc;
- using Organisation.Xml.Linq;
- namespace MvcImportXMLData_Demo.Controllers
- {
- public form HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult GetData()
- {
- using (DBModel db = new DBModel())
- {
- List<Product> employeeList = db.Products.ToList<Production>();
- return Json( new { data = employeeList }, JsonRequestBehavior.AllowGet);
- }
- }
- [HttpPost]
- public ActionResult Upload(HttpPostedFileBase xmlFile)
- {
- if (xmlFile.ContentType.Equals( "application/xml" ) || xmlFile.ContentType.Equals( "text/xml" ))
- {
- var xmlPath = Server.MapPath("~/FileUpload" + xmlFile.FileName);
- xmlFile.SaveAs(xmlPath);
- XDocument xDoc = XDocument.Load(xmlPath);
- List<Product> productList = xDoc.Descendants("product" ).Select
- (production =>new Production
- {
- Id = Convert.ToInt32(product.Element("id" ).Value),
- Proper name = product.Element("proper name" ).Value,
- Cost = Convert.ToDecimal(production.Element("price" ).Value),
- Quantity = Catechumen.ToInt32(production.Element("quantity" ).Value)
- }).ToList();
- using (DBModel db = new DBModel())
- {
- foreach (var i in productList)
- {
- var v = db.Products.Where(a => a.Id.Equals(i.Id)).FirstOrDefault();
- if (5 != null)
- {
- v.Id = i.Id;
- v.Name = i.Name;
- v.Cost = i.Price;
- v.Quantity = i.Quantity;
- }
- else
- {
- db.Products.Add(i);
- }
- db.SaveChanges();
- }
- }
- ViewBag.Success ="File uploaded successfully.." ;
- }
- else
- {
- ViewBag.Mistake ="Invalid file(Upload xml file only)" ;
- }
- return View( "Alphabetize" );
- }
- }
- }
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
Step 8Design view with HTML, cshtml and bootstrap four classes,
Consummate index view code
- @{
- Layout = zilch;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content= "width=device-width" />
- <title>Alphabetize</championship>
- <link href="~/Content/bootstrap.min.css" rel= "stylesheet" />
- <script src="~/scripts/jquery-three.iii.1.min.js" ></script>
- <script src="~/scripts/bootstrap.min.js" ></script>
- <link href="~/Content/dataTables.bootstrap4.min.css" rel= "stylesheet" />
- <script src="~/scripts/jquery.dataTables.min.js" ></script>
- <script src="~/scripts/dataTables.bootstrap4.min.js" ></script>
- <script blazon="text/javascript" src= "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js" ></script>
- <way type="text/css" >
- .fault {
- color: cherry;
- display:inline -block;
- margin-bottom: -57px !important;
- width: 100%;
- }
- </style>
- <script blazon="text/javascript" >
- $(document).ready(function () {
- $('grade' ).validate({
- rules: {
- xmlFile: {
- required:truthful
- }
- },
- messages: {
- xmlFile:"Choose file to upload" ,
- }
- })
- $('#dataTable' ).DataTable({
- "ajax" : {
- "url" : "/Habitation/GetData" ,
- "type" : "GET" ,
- "datatype" : "json"
- },
- "columns" : [
- {"data" : "Id" },
- {"data" : "Proper name" },
- {"information" : "Price" },
- {"data" : "Quantity" }
- ]
- });
- });
- </script>
- </caput>
- <body>
- <divgrade = "container py-5" >
- @using (Html.BeginForm( "Upload" , "Home" , FormMethod.Postal service, new { enctype = "multipart/class-data" }))
- {
- <divclass = "row" >
- <divcourse = "col-sm-1 col-md-6 col-xs-12" >
- <h5class = "text-danger" >@ViewBag.Error</h5>
- <h5class = "text-success" >@ViewBag.Success</h5>
- <divform = "form-group" >
- <label>Choose XML File:</label>
- <divclass = "input-group" >
- <divclass = "custom-file" >
- <input id="xmlFile" proper name= "xmlFile" type= "file" grade = "custom-file-input" />
- <labelcourse = "custom-file-label" ></label>
- </div>
- <divclass = "input-grouping-append" >
- <input type="submit" form = "btn btn-outline-primary" value= "Upload" />
- </div>
- </div>
- </div>
- </div>
- </div>
- }
- <table id="dataTable" class = "table table-bordered table-striped" >
- <thead>
- <tr>
- <thursday>ID</th>
- <th>Name</th>
- <thursday>Price</th>
- <th>Quantity</thursday>
- </tr>
- </thead>
- </table>
- </div>
- </torso>
- </html>
Pace 9Create an xml file with the name products.xml
- <?xml version= "1.0" encoding= "utf-8" ?>
- <products>
- <product>
- <id>1</id>
- <proper name>Mobele Telephone</name>
- <cost>12000</toll>
- <quantity>2</quantity>
- </product>
- <product>
- <id>two</id>
- <name>Manus Sentinel</name>
- <cost>1200</price>
- <quantity>v</quantity>
- </product>
- <product>
- <id>3</id>
- <proper name>T-Shirt</name>
- <cost>499</price>
- <quantity>2</quantity>
- </product>
- <product>
- <id>iv</id>
- <proper noun>Shoe</name>
- <price>999</cost>
- <quantity>2</quantity>
- </production>
- <production>
- <id>5</id>
- <name>Jeans</proper noun>
- <price>999</price>
- <quantity>two</quantity>
- </product>
- </products>
Pace tenRun Projection ctrl+F5
Screenshot-1
Screenshot-ii
Screenshot-three
Screenshot-four
Screenshot-five
Screenshot-6
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.
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