繁体   English   中英

如何使用C#实体框架获取SQL Server表/视图等中每一列的数据类型?

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

如何使用实体框架获取SQL Server表或视图中每一列的类型?

我需要从表中获取所有数据之前执行此操作,因为我想允许用户进行筛选,例如,从实际从SQL Server表/视图中检索数据之前的日期开始进行过滤。

因此,如果我有一个带有发布日期的Books表,我想返回每个列(名称,发布者,发布日期)类型,以便允许事先过滤。 我需要此代码来执行此操作,因为我不一定知道这些列,因为用户可能使用多个不同的表。

.NET Framework类型很好,我不需要SQL Server类型...

这是一些示例代码:

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();
}

编辑:到目前为止,我只能通过获取表中的第一条记录来做到这一点,就像这样...

      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();
        }

但我重复一遍,我不想先获得任何记录。

您可以使用GetProperty ,然后使用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();
        }

Ryios的评论使我想到了必须知道的极其简单的答案,这将为我提供表中每个字段的PropertyInfo数组。

var columns=typeof(tbl_Books).GetProperties();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM