How to construct nested JSON in C#? - c#
Environment:
I have data stored in SQL2000 database and I am using VWD to maintain our company website.
In the past I use asp.net + SQL database as the interface for various department until I met Json.NET.
Business Process:
Here is what I want to realize. I have several tables in our SQL database, from which I can query the project tasks, assignments... based on the users' selection or input in my aspx webpage. I would like to serialize the dataset into JSON for further processing (in a word, it could be visualized in the form as gantt chart in the webpage).
Here below is the JSON example:
{"tasks":[
{"id":-1,"name":"Gantt editor","code":"","level":0,"status":"STATUS_ACTIVE","start":1346623200000,"duration":16,"end":1348523999999,"startIsMilestone":true,"endIsMilestone":false,"assigs":[]},
{"id":-2,"name":"coding","code":"","level":1,"status":"STATUS_ACTIVE","start":1346623200000,"duration":10,"end":1347659999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"description":"","progress":0},
],
"selectedRow":0,
"deletedTaskIds":[],
"canWrite":true,
"canWriteOnParent":true }
In order to do so, I first construct the class based on the JSON format above. Here below is what I wrote:
public class ganttData
{
public class Tasks
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public object start { get; set; }
public int duration { get; set; }
public object end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public List<object> assigs { get; set; }
public string description { get; set; }
public int? progress { get; set; }
public string depends { get; set; }
}
public int selectedRow { get; set; }
public List<object> deletedTaskIds { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
}
The reason why I want to construct the class is that I would like to have a test first and see if the program could work or not.
But it seems it doesn't work out.
For sure you master have better ways to do so but this is the best way that I could come out with after many times of failure attemps.
Current Status:
So far I could successfully retrieve the SQL Table Data as dataset but I don't know how to serialize the retrieved data into JSON.
Millions of thanks for your help.
Schumann
Here below is the code in my ***.aspx.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.IO;
using System.Configuration;
public partial class Test_JNetToFile : System.Web.UI.Page
{
public class ganttData
{
public class Tasks
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public object start { get; set; }
public int duration { get; set; }
public object end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public List<object> assigs { get; set; }
public string description { get; set; }
public int? progress { get; set; }
public string depends { get; set; }
}
//public List<Task> tasks { get; set; }
public int selectedRow { get; set; }
public List<object> deletedTaskIds { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
////get the connection string from web.config
////uncomment the following if you need to access sql database
////---------------------------------- Database connection----------------------------------------------
//string connString = ConfigurationManager.ConnectionStrings["ShipmentConnectionString"].ConnectionString;
//DataSet dataSet = new DataSet();
//using (SqlConnection conn = new SqlConnection(connString))
//{
// SqlDataAdapter adapter = new SqlDataAdapter();
// adapter.SelectCommand = new SqlCommand("select * from Gantt where Nr < 5", conn);
// conn.Open();
// adapter.Fill(dataSet);
//}
//string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
////---------------------------------- Database connection----------------------------------------------
ganttData gd = new ganttData
{
Tasks =
{
{id = -1,name = "Gantt editor","code":"","level":0,"status":"STATUS_ACTIVE","start":1346623200000,"duration":16,"end":1348523999999,"startIsMilestone":true,"endIsMilestone":false,"assigs":[]},
{id = -2,name = "coding","code":"","level":1,"status":"STATUS_ACTIVE","start":1346623200000,"duration":10,"end":1347659999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"description":"","progress":0},
{id = -3,name = "gant part","code":"","level":2,"status":"STATUS_ACTIVE","start":1346623200000,"duration":2,"end":1346795999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":""},
{id = -4,name = "editor part","code":"","level":2,"status":"STATUS_SUSPENDED","start":1346796000000,"duration":4,"end":1347314399999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"3"},
{id = -5,name = "testing","code":"","level":1,"status":"STATUS_SUSPENDED","start":1347832800000,"duration":6,"end":1348523999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"2:5","description":"","progress":0},
{id = -6,name = "test on safari","code":"","level":2,"status":"STATUS_SUSPENDED","start":1347832800000,"duration":2,"end":1348005599999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":""},
{id = -7,name = "test on ie","code":"","level":2,"status":"STATUS_SUSPENDED","start":1348005600000,"duration":3,"end":1348264799999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"6"},
{id = -8,name = "test on chrome","code":"","level":2,"status":"STATUS_SUSPENDED","start":1348005600000,"duration":2,"end":1348178399999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"6"}
},
selectedRow = 0,
deletedTaskIds = [],
canWrite = true,
canWriteOnParent = true
};
// serialize JSON to a string and then write string to a file
File.WriteAllText(#"c:\movie.json", JsonConvert.SerializeObject(movie));
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(#"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, movie);
}
//Label1.Text = json;
}
}
Related
I have 2 json files and i am deserializing them in c#, how can i make a join
I have 2 json files and i am deserializing them separately in blazor c#, how can i make a join. so i can show country name also in page. eg AN = Netherlands . json file 1 is below {"CountryIso2":"AF","CountryName":"Afghanistan"},{"CountryIso2":"AN","CountryName":"Netherlands"} json file 2 is below {"Name":"something","Start":"2021-11-10T09:00:00","End":"2021-11-14T09:00:00","AdditionalInformation":"Volufda.</br>","Address":{"Information":"fasdfas","City":"Pelh\u0159imov, Vyso\u010dina","CountryIso2":"AN"}} my C# code is public class Event { public string Name { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public string AdditionalInformation { get; set; } public Addressar Address { get; set; } } public class Addressar { public string Information { get; set; } public string City { get; set; } public string CountryIso2 { get; set; } } public class Country { public string CountryIso2 { get; set; } public string CountryName { get; set; } } give solutions please.
You can use the Newtonsoft.Json.JsonConvert.DeserializeObject method. Start by parsing the json files into Event and Country objects. Then use the Select() method to combine them. For example, you can do something like this: public void MergeFiles() { // Parse the json files into object lists var countries = JsonConvert.DeserializeObject<List<Country>>(File.ReadAllText("countries.json")); var events = JsonConvert.DeserializeObject<List<Event>>(File.ReadAllText("events.json")); // Create a new list with the result var result = events.Select(x => new { Name = x.Name, Start = x.Start, End = x.End, AdditionalInformation = x.AdditionalInformation, Address = new { Information = x.Address.Information, City = x.Address.City, CountryIso2 = x.Address.CountryIso2, CountryName = countries.First(y => y.CountryIso2 == x.Address.CountryIso2).CountryName } }).ToList(); // Write the result to file File.WriteAllText("Result.txt", JsonConvert.SerializeObject(result); } This will produce a file with json text that contains the events with country names information.
your first json file is invalid , you have to fix it [{"CountryIso2":"AF","CountryName":"Afghanistan"},{"CountryIso2":"AN","CountryName":"Netherlands"}] you can add CountryName property to an Addressar class public class Addressar { public string Information { get; set; } public string City { get; set; } public string CountryIso2 { get; set; } public string CountryName { get; set; } } code using System.Text.Json; Event ev = JsonSerializer.Deserialize<Event>(json2); List<Country> countries = JsonSerializer.Deserialize<List<Country>>(json1); ev.Address.CountryName = countries.Where(c=> c.CountryIso2== ev.Address.CountryIso2) .FirstOrDefault()?.CountryName;
As per the existing structure we can apply a where clause and apply the for single results.If we want to go ahead with multiple results we can make use of foreach in this scenario.Please find the complete c# code.You can format it according to your actual result. **Your First Json Should be List:** **You have to represent like this [ {},{} ]** **[{'CountryIso2':'AF','CountryName':'Afghanistan'},{'CountryIso2':'AN','CountryName':'Netherlands'}]";** **Complete C# Code:** using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Assessment { class P2 { static void Main(string[] args) { string countries = "[{'CountryIso2':'AF','CountryName':'Afghanistan'}, {'CountryIso2':'AN','CountryName':'Netherlands'}]"; List<Country> _countries = JsonConvert.DeserializeObject<List<Country>>(countries); string eventDetails = "{'Name':'something','Start':'2021-11-10T09:00:00','End':'2021-11-14T09:00:00', 'AdditionalInformation':'Volufda.</br>','Address': {'Information':'N\u00e1dra\u017en\u00ed 1536, Pelh\u0159imov', 'City':'Pelh\u0159imov, Vyso\u010dina','CountryIso2':'AN'}}"; Event eventData = JsonConvert.DeserializeObject<Event>(eventDetails); eventData.Address.Country = _countries.Where(p => p.CountryIso2 == eventData.Address.CountryIso2).FirstOrDefault().CountryName; Console.WriteLine(JsonConvert.SerializeObject(eventData)); Console.ReadLine(); } } public class Event { public string Name { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public string AdditionalInformation { get; set; } public Addressar Address { get; set; } } public class Addressar { public string Information { get; set; } public string City { get; set; } public string CountryIso2 { get; set; } public string Country { get; set; } } public class Country { public string CountryIso2 { get; set; } public string CountryName { get; set; } } }
Writing XML based on dynamically generated data
I will be writing an XML file via C# where the data for the elements is dynamic. So typically, I'll have this structure (simplified for the question): <?xml version="1.0" encoding="utf-8"?> <Output xmlns="http://xxxx/xxx.xsd"> <AccountHolder> <Name></Name> <Address1></Address1> <City></City> <State></State> <ZipCode></ZipCode> </AccountHolder> <Visits> <VisitDate></VisitDate> <Copay></Copay> <CoInsurance></CoInsurance> </Visits> <PatientDetails> <AcctNo></AcctNo> <PatientName></PatientName> <Medicare></Medicare> <VisitDetails> <VDate></VDate> <Amount></Amount> <NonCoveredAmount></NonCoveredAmount> </VisitDetails> </PatientDetails> </Output> Now, while there will always be one "Account Holder" there will be anywhere from 0 to multiple visits. Subsequently, there will be list of 0 or more Patients, and then nested within the patients, there will be 0 or more visit details. I do not control the structure. I need to take the collected data I receive and create the XML. I'll be receiving data on a single account holder which may have any number of the subsequent elements. I have classes for AccountHolder, Visit, PatientDetails, and VisitDetails. However, I am unsure as to the best method for building out the XML dynamically as I read the source data? At first, I was thinking on gathering the data in various collections.
Try following : using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; namespace ConsoleApp2 { class Program { const string FILENAME = #"c:\temp\test.xml"; static void Main(string[] args) { Output output = new Output() { Accountholder = new AccountHolder() { Name = "", Address1 = "", City = "", State = "", ZipCode = "" }, Visits = new Visits(), PatientDetails = new PatientDetails() { AccNo = "", PatientName = "", Medicare = "", VisitDetails = new List<VisitDetails>() { new VisitDetails() } } }; XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, "http://xxxx/xxx.xsd"); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter writer = XmlWriter.Create(FILENAME, settings); XmlSerializer serializer = new XmlSerializer(typeof(Output)); serializer.Serialize(writer, output); } } [XmlRoot(Namespace = "http://xxxx/xxx.xsd")] public class Output { public AccountHolder Accountholder { get; set; } public Visits Visits { get; set; } public PatientDetails PatientDetails { get; set; } } public class AccountHolder { public string Name { get; set; } public string Address1 { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } } public class Visits { public DateTime VisitDate { get; set; } public decimal Copay { get; set; } public decimal CoInsurance { get; set; } } public class PatientDetails { public string AccNo { get; set; } public string PatientName { get; set; } public string Medicare { get; set; } [XmlElement] public List<VisitDetails> VisitDetails { get; set; } } public class VisitDetails { public DateTime VDate { get; set; } public decimal Amount { get; set; } public decimal NonCoveredAmount { get; set; } } }
C# - Json Deserialize - Cannot deserialize the Json Object
I am new to using the Json format with serializing and deserializing, I am using Json.Net. As a little activity I decided to use the API from a game that I play to retrieve some simple statistics. However, I am trying to put this Json into classes (created by json2csharp) but I get the exception. Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TornCityAPI.PlayerStatistics.Stats+RootObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. and here is the code. using Microsoft.Win32; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Windows.Forms; namespace TornCityAPI { public partial class Form_Main : Form { // to hold the users api key private string apiKey; public string APIKey { get { return apiKey; } set { apiKey = value; } } // location in the registry private string registryLocation = #"HKEY_CURRENT_USER\TornCityAPI\Watch_App"; public string RegistryLocation { get { return registryLocation; } } // the url which will be used to retrive information private string apiUrl = "https://api.torn.com/user/?selections=&key="; public string ApiUrl { get { return apiUrl; } set { apiUrl = value; } } // in case of a network disconnect, we could server the previous results instead. private string previousTornStats; public string PreviousTronStats { get { return previousTornStats; } set { previousTornStats = value; } } public Form_Main() { InitializeComponent(); } private void Form_Main_Load(object sender, EventArgs e) { CheckNetworkConnection(); // if the api key does not exists within the registry if (Registry.GetValue(registryLocation, "Watch_App", null) == null) { // ask the user to insert theirs and open the form to allow that MessageBox.Show("Please enter your torn API key!"); Form_APIKey apiWindow = new Form_APIKey(); apiWindow.ShowDialog(this); } // otherwise else { // connect the url with the api key to get the full, working url to get the information APIKey = (string)Registry.GetValue(registryLocation, "Watch_App", null); ApiUrl += APIKey; MessageBox.Show(apiUrl); } } private void timer_UpdateStats_Tick(object sender, EventArgs e) { CheckNetworkConnection(); UpdateTornStats(); } void UpdateTornStats() { using (var webClient = new WebClient()) { var json = new WebClient().DownloadString(ApiUrl); var list = JsonConvert.DeserializeObject<List<PlayerStatistics.Stats.RootObject>>(json); Console.WriteLine(list.Count); } } void CheckNetworkConnection() { // if they are not connected to the internet if (NetworkInterface.GetIsNetworkAvailable() == false) { Console.WriteLine("You are not connected to the internet!" + "\n" + "Please connect and restart!"); return; } } } } Specifically: void UpdateTornStats() { using (var webClient = new WebClient()) { var json = new WebClient().DownloadString(ApiUrl); var list = JsonConvert.DeserializeObject<List<PlayerStatistics.Stats.RootObject>>(json); Console.WriteLine(list.Count); } } Here is the class I try to put it into. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TornCityAPI.PlayerStatistics { class Stats { public class Life { public int current { get; set; } public int maximum { get; set; } public int increment { get; set; } public int interval { get; set; } public int ticktime { get; set; } public int fulltime { get; set; } } public class Job { public string position { get; set; } public int company_id { get; set; } public string company_name { get; set; } } public class Faction { public string position { get; set; } public int faction_id { get; set; } public int days_in_faction { get; set; } public string faction_name { get; set; } } public class Married { public int spouse_id { get; set; } public string spouse_name { get; set; } public int duration { get; set; } } public class Icons { public string icon6 { get; set; } public string icon3 { get; set; } public string icon8 { get; set; } public string icon27 { get; set; } public string icon9 { get; set; } } public class RootObject { public string rank { get; set; } public int level { get; set; } public string gender { get; set; } public string property { get; set; } public string signup { get; set; } public int awards { get; set; } public int friends { get; set; } public int enemies { get; set; } public int forum_posts { get; set; } public int karma { get; set; } public int age { get; set; } public string role { get; set; } public int donator { get; set; } public int player_id { get; set; } public string name { get; set; } public int property_id { get; set; } public string last_action { get; set; } public Life life { get; set; } public List<string> status { get; set; } public Job job { get; set; } public Faction faction { get; set; } public Married married { get; set; } public Icons icons { get; set; } } } } I dont really know how to lay this out or what class should be created from the Json. (However I assume its the root as it has references to the other classes) Finally, here is the Json which is downloaded to a string: { "rank": "Reasonable Punchbag", "level": 22, "gender": "Male", "property": "Ranch", "signup": "2013-08-01 07:59:43", "awards": 58, "friends": 2, "enemies": 2, "forum_posts": 25, "karma": 4, "age": 1234, "role": "Civilian", "donator": 1, "player_id": 1761543, "name": "GamingAnonymous", "property_id": 16693, "last_action": "18 minutes ago", "life": { "current": 429, "maximum": 1072, "increment": 53, "interval": 300, "ticktime": 258, "fulltime": 3858 }, "status": [ "In hospital for 3 hrs 4 mins - Hospitalized by someone", "" ], "job": { "position": "Employee", "company_id": 61582, "company_name": "streamTV - hiring 33k man" }, "faction": { "position": "Member", "faction_id": 17845, "days_in_faction": 268, "faction_name": "The Watchers" }, "married": { "spouse_id": 2024099, "spouse_name": "Anonymous_Hugo", "duration": 62 }, "icons": { "icon6": "Male", "icon3": "Donator", "icon8": "Married - To Anonymous_Hugo", "icon27": "Company - Employee of streamTV - hiring 33k man (Television Network)", "icon9": "Faction - Member of The Watchers", "icon15": "Hospital - Hospitalized by someone - 03:04:17 " } } Any help would be greatly appreciated, thanks.
The error message is pretty straightforward. You're trying to deserialize object to List of RootObject. Use this snippet: void UpdateTornStats() { using (var webClient = new WebClient()) { var json = new WebClient().DownloadString(ApiUrl); var list = JsonConvert.DeserializeObject<PlayerStatistics.Stats.RootObject>(json); Console.WriteLine(list.Count); } }
C#: JSON One to Many Data Parse - SSIS Script Component
Any help would be appreciated. I am trying to parse data from a JSON source file in SSIS (SQL Server Integration Services). I can parse through the data but am getting stuck on parsing the data where there is a 'one to many' relationship. There is a data entity repeated several times ("display_k") - "responses": [ {"display_k":"good","answer":null} ,{"display_k":"bad","answer":null} ,{"display_k":"general","answer":"The whole process was Easy. "} ,{"display_k":"would_buy_again","answer":true} ,{"display_k":"happy_with_customer_service","answer":null} ] The full code is below: using System; using System.Data; using Microsoft.SqlServer.Dts.Pipeline.Wrapper; using Microsoft.SqlServer.Dts.Runtime.Wrapper; using System.IO; //using Newtonsoft.Json; using System.Collections.Generic; using System.Runtime.Serialization.Json; using System.Text; [Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute] public class ScriptMain : UserComponent { public override void CreateNewOutputRows() { var filePath = Connections.Connection.AcquireConnection(null).ToString(); using (var fileContents = new StreamReader(filePath)) while (fileContents.Peek() >= 0) { var record = fileContents.ReadLine(); var ser = new DataContractJsonSerializer(typeof(RootObject)); var memStream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(record)); var root = ser.ReadObject(memStream) as RootObject; //reviewables var CustomerExperienceReview = root.customer_experience_reviews; foreach (var CER in CustomerExperienceReview) { OutputBuffer.AddRow(); OutputBuffer.id = CER.id; OutputBuffer.branchattribution = CER.branch_attribution; OutputBuffer.reviewerfirstname = CER.reviewer.first_name; OutputBuffer.reviewerid = CER.reviewer.id; // Cannot get the output buffer to show the correct result: OutputBuffer.responsesdisplaykey = string.Join(",", CER.responses.display_key); } } } public class Pagination { public int total_entries { get; set; } public int current_page { get; set; } public int total_pages { get; set; } public int per_page { get; set; } public object previous_page { get; set; } public int next_page { get; set; } } public class Summary { public Pagination pagination { get; set; } public int moving_window_size { get; set; } public SortOrder sort_order { get; set; } public List<object> sort_orders { get; set; } } public class Reviewer { public string first_name { get; set; } public int id { get; set; } } public class Respons { public string display_key { get; set; } public object answer { get; set; } } public class CustomerExperienceReview { public int id { get; set; } public string branch_attribution { get; set; } public List<Respons> responses { get; set; } } public class RootObject { public Summary summary { get; set; } public List<CustomerExperienceReview> customer_experience_reviews { get; set; } } }
You have: OutputBuffer.responsesdisplaykey = string.Join(",", CER.responses.display_key); Based on the class definitions, CER.responses is a List<Respons>. If you want a comma-separated list of display keys, you'll need to project the Respons objects to strings. OutputBuffer.responsesdisplaykey = string.Join(",", CER.responses.Select(r=>r.display_key));
How do I take an array of deserialized data and store it into entity framework db?
I was able to deserialize my data from using a user import an xml file. Now, I'm wondering how do I take the deserialized xml data and store it into my local database using Entity Framework/ADO.NET? My model: [Serializable] [XmlRoot("lot_information")] public class LotInformation { [Key] public int Id { get; set; } [XmlArray("components")] [XmlArrayItem("component", typeof(Components))] public Components[] components { get; set; } [XmlArray("families")] [XmlArrayItem("control", typeof(Families))] public Families[] families { get; set; } [XmlAttribute("exp_date")] public DateTime exp_date { get; set; } [XmlAttribute("lot_number")] public string lot_number { get; set; } } [Serializable] public class Components { [Key] public int Id { get; set; } [XmlAttribute("control")] public string aControl { get; set; } [XmlAttribute("cal_ref")] public string cal_ref { get; set; } [XmlAttribute("family")] public string family { get; set; } [XmlAttribute("component")] public int component { get; set; } [XmlAttribute("id")] public string componentId { get; set; } [XmlElement("target")] public int target { get; set; } [XmlElement("min")] public int min { get; set; } [XmlElement("max")] public int max { get; set; } [XmlElement("number")] public int number { get; set; } } [Serializable] public class Families { [Key] public int Id { get; set; } [XmlAttribute("family")] public string controlFamily { get; set; } [XmlAttribute("pctrl")] public string pctrl { get; set; } } My dataContext: class DMIDataContext : DbContext { public DbSet<Components> Components { get; set; } public DbSet<Families> Families { get; set; } public DbSet<ReagentLotInformation> ReagentLotInformation {get;set;} public DMIDataContext() : base("DMIConnectionString") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } My viewmodel: Excerpt with db connection: public static void DeSerializationXML(string filePath) { XmlRootAttribute xRoot = new XmlRootAttribute(); xRoot.ElementName = "lot_information"; xRoot.IsNullable = false; // Create an instance of lotinformation class. var lot = new LotInformation(); // Create an instance of stream writer. TextReader txtReader = new StreamReader(filePath); // Create and instance of XmlSerializer class. XmlSerializer xmlSerializer = new XmlSerializer(typeof(LotInformation), xRoot); // DeSerialize from the StreamReader lot = (LotInformation)xmlSerializer.Deserialize(txtReader); // Close the stream reader txtReader.Close(); using (var db = new DMIDataContext()) {LotInformation newLot = new LotInformation(); if (newLot != null) { newLot.Id = lot.Id; newLot.lot_number = lot.lot_number; newLot.exp_date = lot.exp_date; for (int i = 0; i < lot.Components.Length; i++) { newLot.Components[i].aControl = lot.Components[i].aControl; newLot.Components[i].cal_ref = lot.Components[i].cal_ref; newLot.Components[i].family = lot.Components[i].family; newLot.Components[i].component = lot.Components[i].component; newLot.Components[i].componentId = lot.Components[i].componentId; newLot.Components[i].target = lot.Components[i].target; newLot.Components[i].min = lot.Components[i].min; newLot.Components[i].number = lot.Components[i].number; } db.LotInformation.Add(newLot); db.SaveChanges(); The problem I'm having is I'm able to pass exp_date and lot_number to my table just fine. It's just the arrays of Components and Families return NULL. I think it has to do with me passing an array of date into the database but the database does not understand an array. How do I fix my class so that I can pass an array of data into the database? Please let me know if you have any questions. THank you.
You can try this: You can use List instead of ICollection [Serializable] [XmlRoot("lot_information")] public class LotInformation { Public LotInformation() { Components = new List<Components>(); Families = new List<Families>(); } [Key] public int Id { get; set; } [XmlArray("components")] [XmlArrayItem("component", typeof(Components))] public List<Components> Components { get; set; } [XmlArray("families")] [XmlArrayItem("control", typeof(Families))] public List<Families> Families { get; set; } .... } And in your ViewModel: using (var db = new DMIDataContext()) {LotInformation newLot = new LotInformation(); newLot.Id = lot.Id; newLot.lot_number = lot.lot_number; newLot.exp_date = lot.exp_date; foreach (Components comp in lot.Components) { newLot.Components.Add(comp); } foreach (Families fam in lot.Families) { newLot.Families.Add(fam); } db.LotInformation.Add(newLot); db.SaveChanges(); I hope it will help. As you can see in this link, you can use List.