我有許多不同的SQL表具有相同的設計 - 所有的身份和兩個字符串字段具有相同的名稱。我不想寫一組函數來從這些表中獲取值,我想要一個以表爲參數的過程。但是當我開始檢索數據時,它說「不能轉換類型bla-bla-bla」。它需要直接傳遞的類型,這就是我想要避免的。該怎麼辦?統一的SQL獲取與LINQ
/*
defined tables:
create table tableA
(
id int identity not null,
type_code nvarchar(50) not null,
type_description nvarchar(1000) not null
)
same SQL for tableB and tableC
tableA, tableB, tableC
*/
void getAnyId(Table tbl, string codeFilter)
{
var p=(tableA)tbl; // HERE I GET EXCEPTION !!!
var id = p.Where(r=> r.code == codeFilter);
if(id.Count() != 1)
return null;
return id.id;
}
又如:
public Dictionary<string,string> readDataSchemeTypes(tvbaseDataContext dc)
{
Dictionary<string,string> ds = new Dictionary<string,string>();
foreach(var ast in dc.tableA)
ds.Add(ast.type_code, ast.type_description);
return ds;
}
這工作,但我需要的一組功能,每每個表之一。
public Dictionary<string, string> readAnySchemeTypes<T>(System.Data.Linq.Table<T> table) where T:System.Data.Linq.ITable
{
Dictionary<string, string> ds = new Dictionary<string, string>();
foreach (var ast in table)
ds.Add(ast.type_code, ast.type_description); // type_code and type_description are not defined for type T
return ds;
}
本示例不編譯。
你可以發表tableA類的代碼嗎,tableA/B/C類有相同的基類嗎? – 2011-05-18 07:33:33
'tableA'是一個實際的CLR類型嗎?你需要所有的類型嗎? – alexn 2011-05-18 07:34:01
你只是不能使用linq2sql,你可以把它轉換爲IEnumerable,但是你會失去性能。更好的方法是複製這個(相同)代碼爲不同的表,因爲如果你可以看到它相同,它實際上是不一樣的,每個「相同」的字段是不一樣的SQL。 – Cynede 2011-05-18 07:36:18