How can I get data type of each column in a SQL Server table/view etc. using C# Entity Framework?

一笑奈何 提交于 2019-12-25 00:33:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!