2014-03-24 38 views
0

在我們的項目中,我們使用Linq-to-Entities連接到數據庫。爲了讀取有效記錄,讓我們說,表1有方法:通用查詢從不同表中獲取記錄

public List<tableName> GetTableNameRecords() 
{ 
try 
{ 
    return (from x in _context.tableName 
         where x.valid == 1 
         select x).ToList(); 
} 
catch (Exception ex) 
{ 
    throw new Exception(ex.Message); 
} 
} 

它的工作原理,但有一個問題 - 爲每個表,我們需要編寫相同的查詢和唯一的變化表名。有沒有辦法編寫通用方法,我們只能傳遞表名?喜歡的東西:

public List<T> GetRecords<T>() 
{ 
try 
{ 
    return (from x in _context.<T> 
         where x.valid == 1 
         select x).ToList(); 
} 
catch (Exception ex) 
{ 
    throw new Exception(ex.Message); 
} 
} 

感謝您的幫助

+0

要做到這一點你必須改變你的上下文類的擴展。在現實世界中,不是表名,它們是上下文類中的屬性。 –

回答

2

您可以使用反射這一點,但遇到一些比較醜陋的代碼。但是,如果你願意稍微改變你的模型,你可以用一種相對直接的方式做到這一點。

創建具有一個屬性的接口 - valid,就像這樣:

interface IValid 
{ 
    bool valid { get; set; } 
} 

確保所有的模型,有這個有效的字段實現的接口。然後,你可以做這樣的事情:

List<T> GetValid<T>(DbContext context) where T: IValid 
{ 
    return context.Set<T>().Where(x=>x.valid).ToList() 
} 

通過讓模型實現的接口,你可以用普通的LINQ表達,讓編譯器這類東西展現出來。

0

下面是一個使用反射

public static IEnumerable<T> GetRecords<T>(this IEnumerable<T> source) 
    { 
     //check property exists 
     var temp = Activator.CreateInstance(typeof(T), new object[] { }); 
     if (temp.GetType().GetProperty("valid") == null) 
      return source; 

     return (from item in source 
       let table = item.GetType() 
       let property = table.GetProperty("valid") 
       let value = property.GetValue(item, null) 
       where (int)value == 1 
       select item).ToList(); 
    } 

的東西這樣稱呼它

int count = _context.TableName.GetRecords().Count();