user2026086 user2026086 - 21 days ago 8
ASP.NET (C#) Question

How to mock a database table structure in my C# code

I need to create a new database table to hold some business rules, however it will be a while before its implemented (need a DBA). In the meantime I wanted to recreate the data held within my code so I could continue coding and testing it, then switch over to the database once ready.

An example would be a table structure with 10 columns, with the first 4 columns holding unique combinations I would use to pull the associated values in the last 6 columns.

E.g.
Company, State, Type, Number (which I would have the values for), then, Column 5, Column 6, Column 7, Column 8, Column 9, Column 10 that I would then pull the values for.

I looked at hash tables but they seem to be one key to one value pairs, I am not sure if I could use 4 keys to get 6 values.

I know this is vague but hoping someone could point me in the right direction of a data structure I could use (this is only backend by the way, I don't need to display to the user).

Answer

Assuming you're not using an ORM you'd ideally want to use the repository pattern as both @DarrenYoung commented and @axlj provided an answer. You should not tightly join your data layer with your application layer, and this pattern will prevent you from doing that.

However, if you're literally just looking to mock a database table you can use the DataSet and DataTable classes, which provide in-memory database-like and table-like data structures respectively.

Creating the table would be as simple as this:

DataTable myTable = new DataTable("myTable");
DataColumn[] key = new DataColumn[4];
key[0] = new DataColumn("Company", typeof(string));
key[1] = new DataColumn("State", typeof(string));
key[2] = new DataColumn("Type", typeof(string));
key[3] = new DataColumn("Number", typeof(int));
myTable.Add(key[0]);
myTable.Add(key[1]);
myTable.Add(key[2]);
myTable.Add(key[3]);
myTable.Add(new DataColumn("Column6", typeof(string)));
myTable.Add(new DataColumn("Column7", typeof(string)));
myTable.Add(new DataColumn("Column8", typeof(string)));
myTable.Add(new DataColumn("Column9", typeof(string)));
myTable.Add(new DataColumn("Column10", typeof(string)));
myTable.PrimaryKey = key;

You can do a lot more with DataTables, but that's just the basics needed to set it up. Additionally, you mentioned HashTables can only have one key, however you can use a Tuple for your key to join together multiple values as such:

var myHashTable = new HashSet<Tuple<string,string,string,int>, object>();
//Create a key
var key1 = Tuple.Create<string,string,string,int>("blah INC", "NY", "blah", 15);
myHashTable.Add(key1, myObject);