簡體   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