সোমবার, ১৮ নভেম্বর, ২০১৩

Repository Pattern



  • Domain Object mg~n access Kiv‡bvi Rb¨ interface use K‡i data and domain layer Gi g‡a¨ mediate K‡i
  • Repository Pattern use K‡i application G data access logic duplication prevent Kiv hvq|
  • Bnv Øviv database, ORM, WCF dataservices, xml files mg~‡n direct access Kiv hvq|
  • GRb¨ Bnv‡K data access Pattern ejv nq|
  • Repository Pattern use K‡i data access Gi nitty gritty details hide Kiv nq|
  • We can easily query the repository for data objects, without having to know how to provide things like a connection string.
  • Repository Pattern use K‡i provider m¤ú‡K©( †hgb- connection details m¤ú‡K©) †KvbwKQz bv †R‡b I Avgiv data object mg~‡n easily query Ki‡Z cvwi|
  • Repository “freely available in-memory data collection” Gi b¨vq behave K‡i  d‡j Avgiv Lye mn‡RB object mg~n add, delete and update Ki‡Z cvwi|
  • Repository pattern GKwU application Gi data and domain layer Gi g‡a¨ GKwU separation layer add K‡i|
  • d‡j D³ application Gi data access part better testable nq|
  • Bnvi gva¨‡g application G Single Responsibility Principle implement nq|
  • Bnvi gva¨‡g application G Seperation of Concern enable nq|
  • Bnvi gva¨‡g application G Testability  increase nq|
UML Diagram:





Code Example:
·         cÖ_‡g Avgiv IRepository bv‡g GKwU interface define Kwi hvi definition wb¤œiƒc-
using System;
using System.Collections.Generic;

namespace CodeFirstData.DBInteractions
{
public interface IEntityRepository<T> where T : class
{
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
    void Delete(Func<T, Boolean> predicate);
    T GetById(long Id);
    T Get(Func<T, Boolean> where);
    IEnumerable<T> GetAll();
    IEnumerable<T> GetMany(Func<T, bool> where);
}
}    

·         Then Avgiv IRepository class Gi concreate implementation class create Ki‡ev hvi bvg n‡e EntityRepositoryBase.
·         Repository base class CRUD Gi Rb¨ implement Kiv n‡e Ggb mKj method mg~n contain Ki‡e|
·         EntityRepositoryBase Gi definition wb¤œiƒc-
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;

namespace CodeFirstData.DBInteractions
{
public abstract class EntityRepositoryBase<T> where T : class
{
    private CodeFirstContext _dataContext;
    private readonly IDbSet<T> dbset;
    protected EntityRepositoryBase(IDBFactory databaseFactory)
    {
        DatabaseFactory = databaseFactory;
        dbset = DataContext.Set<T>();
    }

    protected IDBFactory DatabaseFactory
    {
        get; private set;
    }

    protected CodeFirstContext DataContext
    {
        get { return _dataContext ?? (_dataContext = DatabaseFactory.Get());}
    }
    public virtual void Add(T entity)
    {
        dbset.Add(entity);          
    }
    public virtual void Update(T entity)
    {
        _dataContext.Entry(entity).State = EntityState.Modified;
    }
    public virtual void Delete(T entity)
    {
        dbset.Remove(entity);          
    }
    public void Delete(Func<T, Boolean> where)
    {
        IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
        foreach (T obj in objects)
            dbset.Remove(obj);
    }
    public virtual T GetById(long id)
    {
        return dbset.Find(id);
    }

    public virtual IEnumerable<T> GetAll()
    {
        return dbset.ToList();
    }
    public virtual IEnumerable<T> GetMany(Func<T, bool> where)
    {
        return dbset.Where(where).ToList();
    }
    public T Get(Func<T, Boolean> where)
    {
        return dbset.Where(where).FirstOrDefault<T>();
    }
}
}

·         Dc‡iv³ EntityRepositoryBase<T> class G Avgiv Av‡iv `ywU class I GKwU interface use K‡iwQ Dnviv n‡jv-
o   CodeFirstContext
o   IDBFactory
o   DBFactory
·         Dnv‡`i ‡Wwd‡bkb wb¤œiƒc-
o   CodeFirstContext :
§  Bnv GKwU Context Class hvnv DbContext †K implement K‡i-
§  DbContext use K‡i Model class mg~‡ni mv‡_ Database Gi connect Kiv‡bv nq|
§  Bnv Model Model class mg~n‡K DbSet<TEntity> Øviv Database Gi mv‡_ Model class / POCO class Gi Mapping K‡i| GLv‡b TEntity n‡”Q Model class / POCO class. hLb Avgiv application ‡K First time run Kiv‡ev ZLb Bnv automatically database I POCO class Gi definition Abyhvqx database Object i.e. Table mg~n create Ki‡e|
§  Database creation Gi †ÿ‡Î cÖ_‡g Bnv web.config / app.configGi g‡a¨ connection string LyR‡e (hvnv dbcontext class Gi same name Gi n‡e|)
§  Bnv hw` †Kvb convention Gi mv‡_ match K‡i Ggb †Kvb connection string bv cvq Z‡e local SQL Express database G database create Ki‡e Ges Dnvi name dbcontext class Gi same name n‡e|
§  Ges database Table mg~‡ni bvg DbSetG defined name Gi same n‡e|
§  GQvov database Gi name dbcontext class Gi constructor GI define Kiv hvq|
§  class Gi definition wb¤œiƒc-
using System.Data.Entity;
using CodeFirstEntities;
namespace CodeFirstData
{
    public class CodeFirstContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
        public virtual void Commit()
        {
            base.SaveChanges();
        }
    }
}

§  Dc‡iv³ definition G Avgiv †`L‡Z cvB
public DbSet<Student> Students { get; set; } G Student
bv‡g GKwU Model / POCO Class use Kiv n‡q‡Q| Bnv Øviv g~jZt Database Gi mv‡_ Model class / POCO class Gi Mapping Kiv n‡q‡Q|
§  GLb Avgiv Student POCO Class Gi definition ‡`L‡ev-
using System.ComponentModel.DataAnnotations;

namespace CodeFirstEntities
{
    public class Student
    {
        public int StudentId { get; set; }
        [Required(ErrorMessage = "Student Name is Mandatory")]
        [StringLength(20, ErrorMessage = "Student name must be less than 20 characters.")]
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public int Age { get; set; }
        public string Country { get; set; }

    }
}
o   IDBFactory
§  IDBFactory GKwU interface hvnv DBFactory class G implement n‡e|
§  Bnvi definition wb¤œiƒc-

using System;

namespace CodeFirstData.DBInteractions
{
    public interface IDBFactory : IDisposable
    {
        CodeFirstContext Get();
    }
}


o   DBFactory
§  Code first entity framework implementing G Risk _v‡K Avi Zv n‡jv hw` Avgiv entity ‡Z †Kvb change Kwi like ‡Kvb property delete / change Kwi Z‡e context database drop Ges recreate K‡i|
§  ‡m‡ÿ‡Î existing data loss n‡e|
§  GB critical situation avoid Kivi Rb¨ Avgiv dataBase Factory Class G DataBase  Class Gi SetInitializer method call Ki‡ev Ges Bnv‡Z null set Ki‡ev|

using System.Data.Entity;

namespace CodeFirstData.DBInteractions
{
public class DBFactory : Disposable, IDBFactory
{

    public DBFactory()
    {
        Database.SetInitializer<CodeFirstContext>(null);
    }

    private CodeFirstContext dataContext;
    public CodeFirstContext Get()
    {
  return dataContext ?? (dataContext = new CodeFirstContext());
    }
    protected override void DisposeCore()
    {
        if (dataContext != null)
            dataContext.Dispose();
    }
}
}

§  DBFactory class Disposable ‡_‡KI inherited nq|
§  Disposable class Gi DisposeCore method use K‡i disposing database resource mg~n release K‡i|
§  Disposable class Gi Definition wb¤œiƒc-
using System;

namespace CodeFirstData.DBInteractions
{
    public class Disposable : IDisposable
    {
        private bool isDisposed;

        ~Disposable()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if (!isDisposed && disposing)
            {
                DisposeCore();
            }

            isDisposed = true;
        }

        protected virtual void DisposeCore()
        {
        }
    }
}

 
§  GLb POCO Class Gi CRUD application handle Kiv‡bvi Rb¨ POCO Class Repository create Ki‡ev| Avgv‡`i POCO Class ‡h‡nZz  Student ‡m‡nZz Avgiv Student Repository Create Ki‡ev|
§  Student Repository `yBwU av‡c m¤úbœ Ki‡Z n‡e-
o   cÖ_‡g GKwU Interface define Ki‡ev Dnvi bvg IStudentRepository 
o   AZtci IStudentRepository ‡K inherit K‡i GKwU class define Ki‡ev hvi bvg StudentRepository.
o   IStudentRepository I StudentRepository Gi definition wb¤œiƒc-
 
IStudentRepository
 
using CodeFirstData.DBInteractions;
using CodeFirstEntities;
 
namespace CodeFirstData.EntityRepositories
{
    public interface IStudentRepository : IEntityRepository<Student>
    {
    }
}
 
 StudentRepository
using CodeFirstData.DBInteractions;
using CodeFirstEntities;
 
namespace CodeFirstData.EntityRepositories
{
    public class StudentRepository : EntityRepositoryBase<Student>, IStudentRepository
    {
        public StudentRepository(IDBFactory databaseFactory)
            : base(databaseFactory)
        {
        }
    }
 
}
 

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন