1

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;
        }
    }
}
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • Reference: http://stackoverflow.com/questions/14603815/how-to-write-below-logic-in-generic-way – LCJ Apr 18 '13 at 07:00

1 Answers1

6

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>();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 1
    Thanks..Now I get the notion of "generics". Use generics when the logic is same for all "types".. – LCJ Jul 02 '12 at 12:36
  • I referred http://msdn.microsoft.com/en-in/library/twcad0zb(v=vs.80).aspx for understanding more about geenerics. But it does not tell the appropriate places where we can use generic methods. Is there any good article that stress points like `Use generic methods when the logic is same for all "types"` ? – LCJ Apr 18 '13 at 07:05