7 Reeds
7 Reeds

Reputation: 2539

C# .Net Entity Framework 6 change DbSet<model class> to List<List<Object>>

I have a project that I am using to learn about EF6. I started the project and setup a database first model. There are a couple of existing tables and views. The result includes "classes" that represent the table / view db structures. My eventual goal is to populate Excel workbook sheets with the results.

I can access and sort, etc, the DbSet data that is returned a la:

using (var db = new TestDbEntities()) {
    var list = db.TestTable1s
                 .OrderBy(m => m.machine.ToUpper())
                 .ThenBy(m => m.netid.ToUpper())
                 .ToList<TestTable1>();

    var columnNames =
            (from t in typeof(TestTable1).GetProperties()
            select t.Name)
            .ToList<string>();
}

However, I am stuck when it comes to getting the column data values. For example, if I add a loop at the bottom of the using above:

    var row = 1;

    foreach (var line in list) {
        var col = 1;

        if (row == 1) {
            //
            // print table headers
            foreach (var item in columnNames) {
                cells[row, col++].Value2(item);
            }

            col = 1;
        }

        //
        // print table "body"
        foreach (var item in line) {
            cells[row, col++].Value2(item);
        }

        row++;
    }

In the "body" loop item is an instance of type TestTable1. I am told by visual studio that TestTable1 is not enumerable.

So my question is, how do I access the members of class TestTable1 in a list-like way? Should I just access each known member as item.memberName?

Upvotes: 0

Views: 124

Answers (1)

Chetan
Chetan

Reputation: 6901

The first list created in your code is the collection of the entities retrieved from the db. And you can loop thru it to create table like structure in the ui.

In fact you can bind this collection to datagridview or datagrid to show the data in tabular format. You just need to know how to use those controls.

If columns in your table are not going to change very frequently then this is the approach you should take.

Upvotes: 1

Related Questions