Home > OS >  How to implement one to many relationship between interfaces in c#?
How to implement one to many relationship between interfaces in c#?

Time:03-21

I want to define 2 interfaces for Bank(IBank) and Account(IAccount). I'm not sure, should I put a list of IAccount into IBank interface or a property of type IBank in IAccount?

My main entity according to the needs of software is IAccount and I just want IBank to find extra information about each account.

here is my primary implementation :

public interface IBank
    {
        int BankId { get; }
        string Name { get; }
        string Description { get; }
        string BranchCode { get; }
        DateTime CreatedAt { get; }
        DateTime ModifiedAt { get; }
        List<IAccount> Accounts { get; }
    }

public interface IAccount
    {
        int Id { get; set; }
        string Name { get; set; }
        DateTime Created { get; set; }
        string AccountNumber { get; set; }                
        int BankId { get; set; }
        decimal Value { get; }        
    }

CodePudding user response:

You need to consider the business relationship that IBank and IAccount should represent.

So I assume that;

  • A bank can have 0, 1, or more bank accounts.
  • A bank account can only be linked to a single bank.

So then we can have the following

public class BankAccount:  IAccount
{
   //other properties
   public IBank AssociatedBank {get; set;}
}

public class Bank:  IBank
{
    //other properties
    public List<IAccount>  BankAccounts { get; set; } = new List<BankAccount>();
}

This way we have the business relationship we want to represent. Each BankAccount is of type IAccount and is linked to a single AssociatedBank, which is of type IBank. Each Bank is of type IBank and has 0,1, or more BankAccounts of type IAccount.

What you need to consider, is do you really need to associate them in both directions? From what you have described, maybe you don't need to have a link from Banks to the accounts and a "one-way" link from BankAccount to a Bank is sufficient.

Your data model should only represent what is really needed in your system, everything else is over-specified. It is tempting to do more, but very important to stick to the specification.

Edit: If this is the case, then you can remove public List<IAccount> BankAccounts { get; set; } ... from your Bank class.

  • Related