Reputation: 411
I am trying to create a repository class for each table. For example I have TableA, TableB and TableC. TableB and TableC has Foreign key to TableA. I created an interface for TableA, TableB and TableC with SaveData() and ListData(). I have MVC form which inserts the data into these tables. When implementing these interface methods do I have to create a seperate class for each interface? Please let me if I am doing right. I appreciate any help.
Public interface ITableA
{
void SaveData(TableAEntity);
List<TableAEntity> ListData();
}
Public interface ITableB
{
void SaveData(TableBEntity);
List<TableBEntity> ListData();
}
Public class ImplementTableA_TableB: ITableA, ITableB
{
public void SaveData(TableAEntity)
{
}
public void SaveData(TableBEntity)
{
}
}
Upvotes: 0
Views: 440
Reputation: 11972
It depends. In fact, when using the repository pattern one should think about aggregates, not tables.
Usually one defines a repository per aggregate in the domain. That is: we don't have a repository per entity! If we have a look at a simple order entry system the entity Order might be the root of a Order aggregate. Thus we will have an Order Repository.
So, yes, depending of your domain model you may end up having just one repository class that is responsible for dealing with two or more entities (or tables). But since I do not know about any particularity of your domain model, I won't be able to tell you if that's the case here.
Please, take a look at here. This is a link to the NHibernate FAQ, but there is relevant information even if you are not using that ORM.
Upvotes: 2
Reputation: 21
The easiest way you can do this is:
Step 1: Create a model for every entity you need.
Eg.
public class BankAccount
{
public virtual int ID { get; set; }
public virtual string BankAccNo { get; set; }
public virtual int BankCode { get; set; }
}
Step 2: Create a Mapping to the database table, using Automapper
Eg.
public class BankAccountMap : ClassMap<BankAccount>
{
public BankAccountMap()
{
Id(x => x.ID);
Map(x => x.BankAccNo);
Map(x => x.BankCode);
Table("dbo.BankAccount");
}
}
Step 3: Create a repository that would do all your database operations.
public class BankAccountRepository : BaseRepository<BankAccount>, IRepository<BankAccount>
{
public BankAccountRepository(ISessionFactoryCreator sessionFactoryCreator) : base(sessionFactoryCreator)
{
_sessionFactory = sessionFactoryCreator.CreateSessionFactory();
}
public BankAccount GetByBankCode(int code)
{
using (var session = _sessionFactory.OpenSession())
{
return session.Linq<BankAccount>().Where(o => o.BankCode == code).ToList<BankAccount>().FirstOrDefault();
}
}
}
Upvotes: 1