Created
August 23, 2019 15:09
-
-
Save csharpfritz/56e5fef9527687b83f6222e528564ac7 to your computer and use it in GitHub Desktop.
Sample code demonstrating Generic Repository pattern with EF Core and C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace WebApplication2.Models | |
{ | |
public interface IGetStoredInDatabase | |
{ | |
public int Id { get; set; } | |
} | |
public interface IRepository<T> where T : IGetStoredInDatabase | |
{ | |
T GetById(int id); | |
IEnumerable<T> Get(); | |
IEnumerable<T> Get(Func<T, bool> where); | |
void Save(T newObject); | |
void Delete(int id); | |
} | |
//public class ProductRepository : IRepository<Product> | |
//{ | |
// public ProductRepository(MyDbContext context) | |
// { | |
// Context = context; | |
// } | |
// public MyDbContext Context { get; } | |
// public void Delete(int id) | |
// { | |
// throw new NotImplementedException(); | |
// } | |
// public IEnumerable<Product> Get() | |
// { | |
// return Context.Products; | |
// } | |
// public IEnumerable<Product> Get(Func<Product, bool> where) | |
// { | |
// return Context.Products.Where(where); | |
// } | |
// public Product GetById(int id) | |
// { | |
// return Context.Products.Find(id); | |
// } | |
// public void Save(Product newObject) | |
// { | |
// throw new NotImplementedException(); | |
// } | |
//} | |
public class ProductRepository : BaseRepository<Product> { | |
public ProductRepository(MyDbContext context) : base(context) { } | |
public override IEnumerable<Product> Get() | |
{ | |
HttpClient.Get("https://github.com/foo"); | |
} | |
} | |
public class BaseRepository<T> : IRepository<T> where T : class, IGetStoredInDatabase | |
{ | |
private readonly MyDbContext context; | |
protected BaseRepository(MyDbContext context) { | |
this.context = context; | |
} | |
public void Delete(int id) | |
{ | |
context.Remove<T>(GetById(id)); | |
} | |
public virtual IEnumerable<T> Get() | |
{ | |
return context.Query<T>().ToList(); | |
} | |
public virtual IEnumerable<T> Get(Func<T, bool> where) | |
{ | |
throw new NotImplementedException(); | |
} | |
public T GetById(int id) | |
{ | |
return context.Query<T>().First(t => t.Id == id); | |
} | |
public void Save(T newObject) | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment