RSS

Tag Archives: POCO

Repository and Unit of Work that is Fully Generic Part 1

So I have been working on creating a generic repository and unit of work and man there are no full examples out there. The following code I wrote is a combination of mine and other peoples work that I referenced combined into what I like to think is a very strong generic unit of work and repository that does not need to have the repositories declared in the unit of work :). Also on your POCO’s if you want EF to throw conncurency errors for Store Wins instead of Client Wins use the timestamp decorator from System.ComponentModel.DataAnnotations. Here is the code

IUnitOfWork

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyCompany.Repo.Generic
{
    public interface IUnitOfWork : IDisposable
    {
        IGenericRepository<T> GetRepository<T>() where T : class;
        void SaveChanges();
        void RollBack();
    }
}

IGenericRepository

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace MyCompany.Repo.Generic
{
    public interface IGenericRepository<T> where T : class
    {
        IQueryable<T> Get { get; }
        IQueryable<T> GetIncluding(params Expression<Func<T, object>>[] includeProperties);
        T Find(object[] keyValues);
        void Add(T entity);
        void Update(T entity);
        void AddOrUpdate(T entity);
        void Delete(object[] keyValues);
    }
}

Base Generic Repository

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyCompany.Repo.Generic
{
    /// <summary>
    /// This class is used to allow you to store the repositories in a collection so they stay in scope 
    /// of the unit of work since in .net there is no class<?> like there is in Java
    /// </summary>
    public abstract class BaseGenericRepository
    {
        public abstract Type Type { get; }
    }
}

Ther rest is to come in part 2

Advertisements
 
1 Comment

Posted by on September 4, 2013 in C#, Entity Framework, Repository, SQL, Unit Of Work

 

Tags: , , , , , ,