正如 casperOne 已经回答的那样,您可以使用ExecuteQuery
方法第一个重载(要求 Type 参数的方法)。因为我有一个类似的问题,你问了一个例子,这里有一个:
public IEnumerable<YourType> RetrieveData(string tableName, string name)
{
string sql = string.Format("Select * FROM {0} where Name = '{1}'", tableName, name);
var result = YourDataContext.ExecuteQuery(typeof(YourType), sql);
return result;
}
请注意,YourType
因为您必须定义一个具有构造函数的类型(它不能是抽象或接口)。我建议您创建一个与您的 SQL 表具有完全相同属性的自定义类型。如果您这样做,ExecuteQuery 方法将自动将表中的值“注入”到您的自定义类型。像那样:
//This is a hypothetical table mapped from LINQ DBML
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientData")]
public partial class ClientData : INotifyPropertyChanging, INotifyPropertyChanged
{
private int _ID;
private string _NAME;
private string _AGE;
}
//This would be your custom type that emulates your ClientData table
public class ClientDataCustomType
{
private int _ID;
private string _NAME;
private string _AGE;
}
因此,在前一个示例中,ExecuteQuery 方法将是:
var result = YourDataContext.ExecuteQuery(typeof(ClientDataCustomType), sql);