从嵌套类动态创建DataTable

时间:2015-04-16 21:45:07

标签: c# .net datatable

我正在尝试从包含一些嵌套类的类中创建C#(.NET 3.5)中的DataTables集合。我基本上得到一个JSON对象,将其解析为RootObject的集合,然后最终将其加载到SQL Server数据库中。我需要一个表低于期望RootObject的每个类,并且理想情况下只有值(?)属性在数据表中有一列。

这是我的课程片段(我的实际课程有5-30个属性):

public class RootObject
{

    [JsonProperty("BaseOrderShipment")]
    public BaseOrderShipment BaseOrderShipment { get; set; }

    [JsonProperty("BaseOrder")]
    public BaseOrder BaseOrder { get; set; }

    [JsonProperty("BaseOrderShipmentLineitem")]
    public IList<BaseOrderShipmentLineitem> BaseOrderShipmentLineitem { get; set; }
}

public class BaseOrderShipment
{

    [JsonProperty("shipment_id")]
    public int ShipmentId { get; set; }

    [JsonProperty("order_id")]
    public int OrderId { get; set; }
}

public class BaseOrder
{

    [JsonProperty("order_id")]
    public int OrderId { get; set; }

    [JsonProperty("ShippingAddress")]
    public ShippingAddress ShippingAddress { get; set; }

    [JsonProperty("BillingAddress")]
    public BillingAddress BillingAddress { get; set; }

    [JsonProperty("Lookup")]
    public IList<Lookup> Lookup { get; set; }
}

public class ShippingAddress
{

    [JsonProperty("ship_address_id")]
    public int ShipAddressId { get; set; }

    [JsonProperty("order_id")]
    public int OrderId { get; set; }

}

public class BillingAddress
{

    [JsonProperty("bill_address_id")]
    public int BillAddressId { get; set; }

    [JsonProperty("order_id")]
    public int OrderId { get; set; }
}

public class Lookup
{

    [JsonProperty("lookup_id")]
    public int LookupId { get; set; }

    [JsonProperty("order_id")]
    public int OrderId { get; set; }
}

public class BaseOrderShipmentLineitem
{

    [JsonProperty("line_item_id")]
    public int LineItemId { get; set; }

    [JsonProperty("order_id")]
    public int OrderId { get; set; }

    [JsonProperty("shipment_id")]
    public int ShipmentId { get; set; }
}

我可以将JSON解析为RootObject

的集合
var obj = ParseOrderShipments(fileName);

public static IList<RootObject> ParseOrderShipments(string fileName)
{
    List<RootObject> retObj = JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(fileName));

    return retObj;
}

我的第一个想法是只是遍历RootObject类来创建一组空表,然后在我将JSON解析为IList<RootObject>之后填充它们。另一个想法是创建DataTable并立即填充它们。我确信这是有争议的,这是更好的方法,所以我愿意接受。

Here's a DotNetFiddle Sample

1 个答案:

答案 0 :(得分:0)

这样的东西会创建一个数据表,您可以更改LINQ查询以合并表中所需的属性。

        List<RootObject> retObj = new List<RootObject>();

        IEnumerable<DataRow> query =
            (from order in retObj.AsEnumerable()
             select new
             {
                 //alter these to build the additional datatable columns you require
                 order.BaseOrder.OrderId,
                 order.BaseOrder.BillingAddress.BillAddressId,
                 order.BaseOrder.ShippingAddress.ShipAddressId
             })
            as IEnumerable<DataRow>;
        DataTable dtbBaseOrder = query.CopyToDataTable<DataRow>();