在LINQ中使用“OfType”LINQ、OfType

2023-09-04 02:31:09 作者:时光作祟不朽间

我从BankAccount类派生两个类 - FixedBankAccount和SavingsBankAccount。这是工作的基础上TPH(表每层次)使用LINQ到SQL。

  [全球:: System.Data.Linq.Mapping.TableAttribute(NAME =dbo.BankAccount)
[InheritanceMapping(code =固定,类型= ty​​peof运算(FixedBankAccount),ISDEFAULT =真)
[InheritanceMapping(code =储蓄,类型= ty​​peof运算(SavingsBankAccount))]
公共抽象部分类的BankAccount:INotifyPropertyChanging,INotifyPropertyChanged的
 

我需要实现的方法GetAllAccountsOfType将返回所有SavingsBankAccount(如果传递的类型是SavingsBankAccount)或FixedBankAccounts(如果传递的类型是FixedBankAccount)。我得到的错误:

  

中的类型或命名空间名称'参数'找不到

与下面的code(使用OfType对LINQ查询)

我们怎样才能使它工作?

存储库:

 命名空间RepositoryLayer
{
    公共类LijosSimpleBankRepository:ILijosBankRepository
    {
        公共System.Data.Linq.DataContext上下文{获得;组; }

        公共虚拟目录< D​​BML_Project.BankAccount> GetAllAccountsOfType(DBML_Project.BankAccount参数)
        {
            VAR的查询=从p在Context.GetTable< D​​BML_Project.BankAccount>()OfType<参数>()
                        选择磷;
        }
    }
}
 
LINQ 标准的查询操作符 过滤 where index1 OfType

解决方案

声明:

 公开的IEnumerable< T> GetAllAccounts< T>()
    其中,T:BankAccount的// T必须继承类的BankAccount,像你的两个子类做
{
    返回Context.GetTable< D​​BML_Project.BankAccount>()OfType< T>();
}
 

用法:

  VAR allSaving = GetAllAccounts< SavingsBankAccount>();
变种allFixed = GetAllAccounts&其中; FixedBankAccount>();
 

I have two classes derived from BankAccount class – FixedBankAccount and SavingsBankAccount. This is working based on "TPH (Table Per Hierarchy)" with 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

I need to implement a method GetAllAccountsOfType which will return all the SavingsBankAccount (if the type passed is SavingsBankAccount) or FixedBankAccounts (if the type passed is FixedBankAccount). I am getting error:

The type or namespace name 'param' could not be found"

with the following code (which uses "OfType" on LINQ query)

How can we make it working?

Repository:

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;
        }
    }
}

解决方案

Declaration:

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>();
}

Usage:

var allSaving = GetAllAccounts<SavingsBankAccount>();
var allFixed = GetAllAccounts<FixedBankAccount>();