EF4+Repository+UnitOfWork 코드 발췌문

41784 단어 repository
IContextFactory.cs
using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



//IDbContextFactory.cs

namespace EFCodeFirstTest.Data

{

    public interface IDbContextFactory<TContext> where TContext:DbContext,new()

    {

        TContext GetDbContext();

    }

}

DbContextFactory.cs
using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    //DbContextFactory.cs

    public class DbContextFactory<TContext>:IDbContextFactory<TContext>,IDisposable

        where TContext:DbContext,new()

    {

        private string _connectionString;

        private TContext _context;



        public DbContextFactory()

        {

            _connectionString = ConfigurationManager.ConnectionStrings["dbContext"].ConnectionString;

            _context.Database.Connection.ConnectionString = _connectionString;

            _context = Activator.CreateInstance<TContext>();

        }



        public DbContextFactory(string connectionString) : this()

        {

            _connectionString = connectionString;

        }



        public TContext GetDbContext()

        {

            return _context == null ? Activator.CreateInstance<TContext>() : _context;

        }



        public void Dispose()

        {

            if (_context != null)

                _context.Dispose();



            GC.SuppressFinalize(this);

        }

    }

}

IGenericRepository.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Linq.Expressions;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    public interface IGenericRepository<TEntity>:IDisposable

        where TEntity:class

    {

        /// <summary>

        /// Gets all objects from database

        /// </summary>

        IQueryable<TEntity> GetAll();



        /// <summary>

        /// Gets objects from database by filter.

        /// </summary>

        /// <param name="predicate">Specified a filter</param>

        IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> predicate);



        /// <summary>

        /// Gets objects from database with filting and paging.

        /// </summary>

        /// <typeparam name="Key"></typeparam>

        /// <param name="filter">Specified a filter</param>

        /// <param name="total">Returns the total records count of the filter.</param>

        /// <param name="index">Specified the page index.</param>

        /// <param name="size">Specified the page size</param>

        IQueryable<TEntity> Filter<Key>(Expression<Func<TEntity, bool>> filter,

            out int total, int index = 0, int size = 50);



        /// <summary>

        /// Gets objects from database with filter and orderby and include fields

        /// </summary>

        /// <param name="filter">can be null</param>

        /// <param name="orderBy">default is null</param>

        /// <param name="includeProperties">string split by ','</param>

        /// <returns></returns>

        IQueryable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>,

            IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");



        /// <summary>

        /// 

        /// </summary>

        /// <param name="total"></param>

        /// <param name="filter"></param>

        /// <param name="orderBy"></param>

        /// <param name="includeProperties"></param>

        /// <param name="index"></param>

        /// <param name="size"></param>

        /// <returns></returns>

        IQueryable<TEntity> GetPaged(out int total, Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>,

            IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "", int index = 0, int size = 50);



        /// <summary>

        /// Gets the object(s) is exists in database by specified filter.

        /// </summary>

        /// <param name="predicate">Specified the filter expression</param>

        bool Contains(Expression<Func<TEntity, bool>> predicate);



        /// <summary>

        /// Find object by keys.

        /// </summary>

        /// <param name="keys">Specified the search keys.</param>

        TEntity Find(params object[] keys);



        /// <summary>

        /// Find object by specified expression.

        /// </summary>

        /// <param name="predicate"></param>

        TEntity Find(Expression<Func<TEntity, bool>> predicate);



        /// <summary>

        /// Create a new object to database.

        /// </summary>

        /// <param name="t">Specified a new object to create.</param>

        void Create(TEntity t);



        /// <summary>

        /// Delete the object from database.

        /// </summary>

        /// <param name="t">Specified a existing object to delete.</param>        

        void Delete(TEntity t);



        /// <summary>

        /// Delete objects from database by specified filter expression.

        /// </summary>

        /// <param name="predicate"></param>

        void Delete(Expression<Func<TEntity, bool>> predicate);



        /// <summary>

        /// Update object changes and save to database.

        /// </summary>

        /// <param name="t">Specified the object to save.</param>

        void Update(TEntity t);



        /// <summary>

        /// To Save all the changes 

        /// </summary>

        /// <returns></returns>

        int Save();



        /// <summary>

        /// Get the total objects count.

        /// </summary>

        int Count { get; }



        /// <summary>

        /// Get the object by execute the raw sql statements.

        /// </summary>

        /// <param name="query"></param>

        /// <param name="parameters"></param>

        /// <returns></returns>

        IQueryable<TEntity> GetWithRawSql(string query, params object[] parameters);

    }

}

GenericRepository.cs
using System;

using System.Collections.Generic;

using System.Data;

using System.Data.Entity;

using System.Linq;

using System.Linq.Expressions;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    public abstract class GenericRepository<TContext, TEntity> : IGenericRepository<TEntity>

        where TContext : DbContext, new()

        where TEntity : class

    {

        protected TContext _context;

        protected IDbContextFactory<TContext> _dbContextFactory;

        protected readonly IDbSet<TEntity> _set;



        protected GenericRepository(IDbContextFactory<TContext> dbContextFactory)

        {

            _dbContextFactory = dbContextFactory;

            _context = _dbContextFactory.GetDbContext();

            _set = _context.Set<TEntity>();

        }



        protected TContext Context

        {

            get

            {

                return _context;

            }

        }



        protected IDbSet<TEntity> DbSet

        {

            get

            {

                return _set == null ? _context.Set<TEntity>() : _set;

            }

        }



        public IQueryable<TEntity> GetAll()

        {

            return DbSet.AsQueryable();

        }



        public IQueryable<TEntity> GetPaged(out int total, Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>,

            IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "", int index = 0, int size = 50)

        {

            int skipCount = index * size;

            var _reset = Get(filter, orderBy, includeProperties);

            _reset = skipCount == 0 ? _reset.Take(size) : _reset.Skip(skipCount).Take(size);

            total = _reset.Count();

            return _reset.AsQueryable();

        }



        public IQueryable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>,

            IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")

        {

            IQueryable<TEntity> query = DbSet;



            if (filter != null)

            {

                query = query.Where(filter);

            }



            foreach (var includeProperty in includeProperties.Split

                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))

            {

                query = query.Include(includeProperty);

            }



            if (orderBy != null)

            {

                return orderBy(query).AsQueryable();

            }

            else

            {

                return query.AsQueryable();

            }

        }





        public IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> predicate)

        {

            return DbSet.Where(predicate).AsQueryable<TEntity>();

        }



        public IQueryable<TEntity> Filter<Key>(Expression<Func<TEntity, bool>> filter, out int total, int index = 0, int size = 50)

        {

            int skipCount = index * size;

            var _resetSet = filter != null ? DbSet.Where(filter).AsQueryable() : DbSet.AsQueryable();

            _resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);

            total = _resetSet.Count();

            return _resetSet.AsQueryable();

        }



        public bool Contains(Expression<Func<TEntity, bool>> predicate)

        {

            return DbSet.Count(predicate) > 0; ;

        }



        public virtual TEntity Find(params object[] keys)

        {

            return DbSet.Find(keys);

        }



        public virtual TEntity Find(Expression<Func<TEntity, bool>> predicate)

        {

            return DbSet.FirstOrDefault(predicate);

        }



        public virtual void Create(TEntity t)

        {

            DbSet.Add(t);

        }



        public virtual void Delete(TEntity t)

        {

            if (Context.Entry(t).State == EntityState.Detached)

            {

                DbSet.Attach(t);

            }

            DbSet.Remove(t);

        }



        public virtual void Delete(Expression<Func<TEntity, bool>> predicate)

        {

            var toDelete = Filter(predicate);

            foreach (var obj in toDelete)

            {

                DbSet.Remove(obj);

            }

        }



        public void Update(TEntity t)

        {

            var entry = Context.Entry(t);

            DbSet.Attach(t);

            entry.State = EntityState.Modified;

        }



        public int Save()

        {

            return Context.SaveChanges();

        }



        public int Count

        {

            get { return DbSet.Count(); }

        }



        public IQueryable<TEntity> GetWithRawSql(string query, params object[] parameters)

        {

            return Context.Database.SqlQuery<TEntity>(query, parameters).AsQueryable();

        }



        public void Dispose()

        {

            if (Context != null)

                Context.Dispose();

            GC.SuppressFinalize(this);

        }

    }

}

IUnitOfWork.cs
using System;



namespace EFCodeFirstTest.Data

{

    public interface IUnitOfWork

    {

        void Commit();

    }

}

UnitOfWork.cs
using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    public class UnitOfWork<TContext>:IUnitOfWork

        where TContext : DbContext,new()

    {

        private IDbContextFactory<TContext> _dbContextFactory;

        private TContext _context;



        public UnitOfWork(IDbContextFactory<TContext> dbContextFactory)

        {

            _dbContextFactory = dbContextFactory;

            _context = _dbContextFactory.GetDbContext();

        }



        public TContext Context

        {

            get

            {

                return _context ?? (_context = _dbContextFactory.GetDbContext());

            }

        }



        public void Commit()

        {

            Context.SaveChanges();

        }

    }

}

IProductContext.cs
using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    public interface IProductContext

    {

        IDbSet<Product> Products { get; }

        IDbSet<Category> Categories { get; }

    }

}

ProductContext.cs
using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    public class ProductContext:DbContext,IProductContext

    {

        public ProductContext(string connectionString)

            : base(connectionString)

        {

            this.Database.Connection.ConnectionString = connectionString;

            

        }

       

        //public DbSet<Product> Products { get; set; }

        private IDbSet<Category> _categories = null;

        public IDbSet<Category> Categories

        {

            get

            {

                return _categories == null ? Set<Category>() : _categories;

            }

        }



        private IDbSet<Product> _products = null;

        public IDbSet<Product> Products

        {

            get

            {

                return _products == null ? this.Set<Product>() : _products;

            }

        }



        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            

            modelBuilder.Entity<Product>().HasKey(b=>b.ProductId);

        }

    }

}

Entities.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace EFCodeFirstTest.Data

{

    public class Product

    {

        public int ProductId { get; set; }

        public string Name { get; set; }

        public Category Category { get; set; }

    }

    public class Category

    {

        public string CategoryId { get; set; }

        public string Name { get; set; }

        public ICollection<Product> Products { get; set; }

    }

}

좋은 웹페이지 즐겨찾기