0

I'm currently storing the data of my application using a simple binary formatter. I'd like to move from the binary formatter to a SQL implementation, for the following reasons:

  • Enable concurrent use of the application on a common data source
  • Moving away from a 'proprietary' format that can easily corrupt and potentially be inaccessible from other platforms/applications (even other assemblies)

I'm implementing Entity Framework code first to design my database. My question revolves around the storage of DataTable fields. Say I have the following object:

public class Person
{
    public string Name {get;set;}
    public DataTable TableOfInformation {get;set;}
}

Saving the string "Name" to a column is simple enough. In order to save the DataTable, I've tried converting to a list of datatable entries. Currently I'm leaning towards simply using XML serialization and saving the DataTable as a string column.

Is this the best way of saving a DataTable field, and are there any concerns with this approach?

3
  • DataTable is really ,not designed for using it with EF. Just deserialize your data into POCO object which will much more work easily with Code First. Nov 12, 2015 at 20:32
  • 1
    You should take this one step further and also store the DataTable as a database table. Nov 12, 2015 at 22:17
  • You can convert DataTable to XML with DataTable.WriteXml method. However, this is anyway the wrong approach. Nov 13, 2015 at 0:08

2 Answers 2

1

I would not recommend storing a DataTable as a field.. it makes more sense to create an actual table instead. That being said, if you still wish to proceed with this, it's not that difficult really. Here's an example:

public class Person
{
    public string Name { get; set; }

    public string TableOfInformationXml { get; set; }

    [NotMapped] // <-- This is important, since you will only store the TableOfInformationXml field
    public DataTable TableOfInformation
    {
        get
        {
            if (string.IsNullOrWhiteSpace(TableOfInformationXml))
            {
                return new DataTable();
            }
            var set = new DataSet();
            using (var reader = new StringReader(TableOfInformationXml))
            {
                set.ReadXml(reader);
            }
            return set.Tables[0];
        }
        set
        {
            var set = new DataSet();
            set.Tables.Add(value);
            var sb = new StringBuilder();
            using (var stringWriter = new StringWriter(sb))
            {
                set.WriteXml(stringWriter);
            }
            TableOfInformationXml = sb.ToString(); 
        }
    }
}

And FYI: You might also consider storing it as JSON instead of XML... in which case, use the following :

[NotMapped]
public DataTable TableOfInformation
{
    get
    {
        if (string.IsNullOrWhiteSpace(TableOfInformationJson))
        {
            return new DataTable();
        }
        return TableOfInformationJson.JsonDeserialize<DataTable>();
    }
    set { TableOfInformationJson = value.ToJson(); }
}

Here I have 2 extension methods as follows:

public static string ToJson<T>(this T item)
{
    return JsonConvert.SerializeObject(item);
}

public static T JsonDeserialize<T>(this string json)
{
    return JsonConvert.DeserializeObject<T>(json);
}
4
  • Thank you very much for this. I understand that this is not ideal from an indexing perspective, or ensuring that all the data in the database is queryable. However I don't know of a simple and easy to implement way to rather create an actual table instead. The DataTable can be any dimension (depends on the user, and I don't know beforehand), and can change dimension size in the application. One class can also have multiple tables, and I'd like to be able to manage them easily. Is there a reason why I should rather consider JSON (is it more platform independent)? Nov 13, 2015 at 7:29
  • @User_FSharp1123, I'm not sure what you mean regarding dimension size. As for JSON vs XML, there's no big difference really, except that JSON will surely take up less space. As for performance, I honestly couldn't say whether serializing/deserializing JSON would be any quicker than doing so with XML.. you may be able to find some info online about that or make some kind of console test app to investigate it further. Other than that, it would just be a matter of personal preference really, I suppose.
    – Matt
    Nov 14, 2015 at 7:12
  • So what I mean by dimension size, is that I do not see how I can follow the approach specified by Amadeus, as it would need to have a property for each column in the DataTable (rows obviously won't be a problem). I however do not know how many columns there will be (could be 10, could be 100, it's user-dependent), as so that is why I think the solution as you have set out here makes more sense. I'm keen to go for the XML approach, as it seems that it's easy to parse in both .NET and in the SQL database. Nov 15, 2015 at 16:10
  • @User_FSharp1123, sure thing... just remember to mark this as the answer if that's the case.
    – Matt
    Nov 15, 2015 at 23:11
0

You can create a model that has all the fields in your DataTable.

public class PersonData
{
  public string Address { get; set;}
  public bool IsStackOverflowUser {get; set;}
  public int Age {get; set;}
} 

Then you can add a PersonData property to your Person model

public class Person
{
  public string Name {get; set;}
  public PersonData PersonalInformation {get; set;}
}
3
  • So although this would be the ideal situation, I don't know the fields in the DataTable to that extent. They are created dynamically, as it is a 2-dimensional data structure containing doubles, i.e. can be 10x4, or 20x6, or whatever the case may be. The dimension can also change for a specific instance of the Person class (changing from 10x4 to 10x6 for example). Nov 13, 2015 at 7:25
  • Important to also note that it doesn't contain only doubles (as otherwise I would've used an array), but contains a combination of strings and double/int values. The Person class will be part of a hierarchy (e.g. Parent, GrandParent, Siblings), of which each class can contain multiple DataTables not necessarily of the same dimension. Nov 13, 2015 at 7:42
  • That sounds like a case for ExpandoObjects. You can try to parse all of the cell contents as strings and then use the Int32.TryParse and Double.TryParse methods to parse any int or doubles that are in the DataTable. Nov 13, 2015 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.