using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using NzbDrone.Core.Tv; using ServiceStack.OrmLite; namespace NzbDrone.Core.Datastore { public interface IBasicRepository where TModel : ModelBase, new() { IEnumerable All(); int Count(); TModel Get(int id); TModel Single(Expression> predicate); TModel SingleOrDefault(); TModel SingleOrDefault(Expression> predicate); List Where(Expression> predicate); TModel Insert(TModel model); TModel Update(TModel model); TModel Upsert(TModel model); void Delete(int id); void Delete(TModel model); void InsertMany(IList model); void UpdateMany(IList model); void DeleteMany(List model); void Purge(); bool HasItems(); void DeleteMany(IEnumerable ids); void UpdateOnly(TModel model, Expression> onlyFields); } public class BasicRepository : IBasicRepository where TModel : ModelBase, new() { public BasicRepository(IDbConnection database) { Database = database; } public IDbConnection Database { get; private set; } public IEnumerable All() { return Database.Select(); } public int Count() { return (int)Database.Count(); } public TModel Get(int id) { return Database.GetById(id); } public TModel Single(Expression> predicate) { return Database.Select(predicate).Single(); } public TModel SingleOrDefault() { return All().Single(); } public TModel Single() { throw new System.NotImplementedException(); } public TModel SingleOrDefault(Expression> predicate) { return Database.Select(predicate).SingleOrDefault(); } public List Where(Expression> predicate) { return Database.Select(predicate); } public TModel Insert(TModel model) { Database.Insert(model); model.Id = (int)Database.GetLastInsertId(); return model; } public TModel Update(TModel model) { Database.Update(model); return model; } public void Delete(TModel model) { Database.Delete(model); } public void InsertMany(IList models) { Database.InsertAll(models); } public void UpdateMany(IList models) { Database.UpdateAll(models); } public void DeleteMany(List models) { Database.DeleteAll(models); } public TModel Upsert(TModel model) { if (model.Id == 0) { Database.Insert(model); model.Id = (int)Database.GetLastInsertId(); return model; } Database.Update(model); return model; } public void Delete(int id) { Database.DeleteById(id); } public void DeleteMany(IEnumerable ids) { Database.DeleteByIds(ids); } public void Purge() { Database.DeleteAll(); } public bool HasItems() { return Count() > 0; } public void UpdateOnly(TModel model, Expression> onlyFields) { Database.UpdateOnly(model, onlyFields); } } }