1

How do you get the column names from a db?

Currently, I'm interacting with the db through linq-sql using an ado.net entity model. I've searched through StackOverflow and I got a few helpful posts but nothing I've tried has worked.

Like take this post:

How do I return the column names of a LINQ entity

I tried the responses from Conrad Frix but they didn't work. I'm not exactly sure what he means by a 'Datacontext' anyway. Is that Entity?

    AttributeMappingSource mappping = new System.Data.Linq.Mapping.AttributeMappingSource();
    var model = mappping.GetModel(typeof (AdoModelEntities));
    var table = model.GetTable(typeof (TableName));

    var qFields= from fields in table.RowType.DataMembers
            where fields.IsPersistent == true
            select fields;

    foreach (var field in qFields)
        Console.WriteLine(field.Name);

This doesn't work because table is null

1 Answer 1

2

You can do something like this...

Object LinqObject = Activator.CreateInstance(tableName, null);

//For each field in the database (or property in Linq object)
foreach (PropertyInfo pi in LinqObject.GetType().GetProperties())
{     
     String name = pi.Name;
}

LinqObject would be the table object you are trying to get names on. It doesn't matter how you create it. That's a way to create it if you just have the string name.

Assuming your .dbml had a table named "Order" it would work just as well to do:

Object LinqObject = new Order();

You don't have to declare the reference to the table object as an Object either obviously.

Sign up to request clarification or add additional context in comments.

2 Comments

I was able to get it working by changing a few things slightly. TableObject LinqObject = new TableObject();
I was actually changing that while you were making your comment in case it was confusing. Thanks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.