2012-07-02 27 views
1

我有兩個派生自BankAccount類的類 - FixedBankAccount和SavingsBankAccount。這是基於「TPH(Table Per Hierarchy)」和LINQ to SQL的工作。在LINQ中使用「OfType」

[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; 
     } 
    } 
} 
+0

參考:http://stackoverflow.com/questions/14603815/how-to-write-低於邏輯的通用方式 – Lijo

回答

5
宣言

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>(); 
+1

謝謝..現在我得到了「泛型」的概念。當所有「類型」的邏輯相同時使用泛型。 – Lijo

+1

@Lijo:很高興幫助! :) – abatishchev

+0

我參考http://msdn.microsoft.com/en-in/library/twcad0zb(v=vs.80).aspx瞭解更多有關通用技術的信息。但它並沒有告訴適當的地方我們可以使用泛型方法。是否有任何好的文章強調像'當所有類型的邏輯相同'使用泛型方法''? – Lijo