Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- namespace tacRepository
- {
- public interface IDbSet<T>: IQueryable<T>
- {
- void Add(T data);
- void Remove(T data);
- }
- public interface IDbContext: IDisposable
- {
- IDbSet<T> GetDbSet<T>();
- void Attach<T>(T data);
- void SubmitChanges();
- }
- public class Person: IIdentifiableObject<Guid>
- {
- public Guid Id { get; set; }
- public string Name { get; set; }
- }
- public class Apartment: IIdentifiableObject<Guid>
- {
- public Guid Id { get; set; }
- }
- public interface IIdentifiableObject<out T>
- where T: struct
- {
- T Id { get; }
- }
- public class Repository<TData, TIdentifier>: IDisposable
- where TIdentifier : struct
- where TData : class, IIdentifiableObject<TIdentifier>
- {
- private readonly IDbContext _dbContext;
- public Repository(IDbContext dbContext)
- {
- _dbContext = dbContext;
- }
- public TData Load(TIdentifier id)
- {
- var result = _dbContext.GetDbSet<TData>().SingleOrDefault(d => d.Id == id);
- if (result == null)
- throw new ArgumentOutOfRangeException("id", id, "Object not found");
- return result;
- }
- public IEnumerable<TData> LoadAll()
- {
- return _dbContext.GetDbSet<TData>();
- }
- public IEnumerable<TData> Load(Expression<Func<TData, bool>> criteria)
- {
- return _dbContext.GetDbSet<TData>().Where(criteria);
- }
- public void Insert(TData data)
- {
- _dbContext.GetDbSet<TData>().Add(data);
- _dbContext.SubmitChanges();
- }
- public void Update(TData data)
- {
- _dbContext.Attach(data);
- _dbContext.SubmitChanges();
- }
- public void Delete(TData data)
- {
- _dbContext.GetDbSet<TData>().Remove(data);
- _dbContext.SubmitChanges();
- }
- public void Dispose()
- {
- _dbContext.Dispose();
- }
- }
- public class UsageSample
- {
- private readonly Repository<Person, Guid> _repository;
- public UsageSample(Repository<Person, Guid> repository)
- {
- _repository = repository;
- }
- public void PrintPersons()
- {
- foreach (var person in _repository.LoadAll())
- {
- Console.WriteLine(person.Name);
- }
- }
- public void AddPerson(string name)
- {
- var person = new Person
- {
- Id = Guid.NewGuid(),
- Name = name
- };
- _repository.Insert(person);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement