问题
How can I get the type of each column in a SQL Server table or view using Entity Framework?
I need to do this BEFORE I get all the data from the table, because I want to allow users to filter, for example, from a date before the data is actually retrieved from the SQL Server table/view.
So if I had a table of Books
with a publish date, I would like to return each column (Name, Publisher, Publish Date) type in order to allow filtering beforehand. I need this code to do this because I will not necessarily know the columns, since the user may use several different tables.
The .NET Framework type is fine, I don't need the SQL Server type...
Here's some example code:
using (var ArgoEntities = new ARGOEntities())
{
//find the types here before the user performs the query so i can build the below code
var query = from b in ArgoEntities.tbl_Books
where b.PublishDate>[user specified date] //some date here the user enters
select b;
var book = query.First();
}
EDIT: I can do this so far only by getting the first record in the table, like this...
using (ARGOEntities ArgoEntities = new ARGOEntities())
{
//var fred = typeof(ARGOEntities).GetProperties();
//var fred = ArgoEntities.GetType().GetProperties();
var a=ArgoEntities.tbl_Books.FirstOrDefault();
var b = ObjectContext.GetObjectType(a.GetType());
var c=b.GetProperties();
}
but i repeat, I DON'T want to get any records first.
回答1:
you can use the GetProperty
and then PropertyType
:
using (var ArgoEntities = new ARGOEntities())
{
//find the types here before the user performs the query so i can build the below code
//Like this you can retrieve the types:
foreach (string propertyName in ArgoEntities.CurrentValues.PropertyNames)
{
var propertyInfo = ArgoEntities.Entity.GetType().GetProperty(propertyName);
var propertyType = propertyInfo.PropertyType;
}
//
var query = from b in ArgoEntities.tbl_Books
where b.PublishDate>[user specified date] //some date here the user enters
select b;
var book = query.First();
}
回答2:
Ryios' comment lead me to the extremely simple answer I knew it had to be, which will give me an array of PropertyInfo for each field in the table.
var columns=typeof(tbl_Books).GetProperties();
来源:https://stackoverflow.com/questions/28099847/how-can-i-get-data-type-of-each-column-in-a-sql-server-table-view-etc-using-c-s