我有两个派生自 BankAccount 类的类——FixedBankAccount 和 SavingsBankAccount。这是基于“TPH(每个层次结构的表)”和 LINQ to SQL 工作的。
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.BankAccount")]
[InheritanceMapping(Code = "Fixed", Type = typeof(FixedBankAccount), IsDefault = true)]
[InheritanceMapping(Code = "Savings", Type = typeof(SavingsBankAccount))]
public abstract partial class BankAccount : INotifyPropertyChanging, INotifyPropertyChanged
我需要实现一个方法 GetAllAccountsOfType,它将返回所有 SavingsBankAccount(如果传递的类型是 SavingsBankAccount)或 FixedBankAccounts(如果传递的类型是 FixedBankAccount)。我收到错误:
The type or namespace name 'param' could not be found”
使用以下代码(在 LINQ 查询中使用“OfType”)
我们怎样才能让它发挥作用?
存储库:
namespace RepositoryLayer
{
public class LijosSimpleBankRepository : ILijosBankRepository
{
public System.Data.Linq.DataContext Context { get; set; }
public virtual List<DBML_Project.BankAccount> GetAllAccountsOfType(DBML_Project.BankAccount param)
{
var query = from p in Context.GetTable<DBML_Project.BankAccount>().OfType<param>()
select p;
}
}
}
最佳答案
声明:
public IEnumerable<T> GetAllAccounts<T>()
where T : BankAccount // T must inherit class BankAccount, like your two sub-classes do
{
return Context.GetTable<DBML_Project.BankAccount>().OfType<T>();
}
用法:
var allSaving = GetAllAccounts<SavingsBankAccount>();
var allFixed = GetAllAccounts<FixedBankAccount>();
关于c# - 在 LINQ 中使用 “OfType”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11293732/