Getting column names from ado.net entity model
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 开发者_如何学Pythonbut 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
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.
精彩评论