I am trying to import a JSON file into SQL server via a .Net Core application.
I have set up my classes using the tool in VS which converts a JSON doc to classes. I then used this to create database using the EF Core migration.
I have deserialised the JSON into my RootObject class using the following:
RootObject rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonFromFile);
I can expand the RootObject object and all looks good, I can see each field and it contains the right data.
I then want to insert this data into the database, I currently have:
var mySolve = new RootObject
{
uuid = rootObject.uuid,
solution = new Solution { gross_margin = rootObject.solution.myValue, imbalances = rootObject.solution.imbalances }
};
db.RootObjects.Add(mySolve);
db.SaveChanges();
db.Dispose();
The problem is that the imbalances class is a list in the json file as seen below:
"solution": {
"myValue": 9999.99,
"imbalances": [
{
"commodity": "Value1",
"name": "Val1",
"direction": "INPUT",
"amount": 1.419884
},
{
"commodity": "Value2",
"name": "Val2",
"direction": "INPUT",
"amount": 1.419884
}
]
}
The Class for imbalances in my app looks like this:
public class Imbalance
{
public int Id { get; set; }
public string commodity { get; set; }
public string name { get; set; }
public string direction { get; set; }
public float amount { get; set; }
}
My app throws an exception on db.RootObjects.Add(mySolve); of:
The type of navigation property 'imbalances' on the entity type 'Solution' is 'Imbalance[]' which is an array type. Collection navigation properties cannot be arrays.
How can insert this object into my database?
UPDATE
I have a table for every section in the JSON file as my class library was auto generated from the JSON file. The imbalances table looks like this:
