Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created September 20, 2022 18:52
Show Gist options
  • Select an option

  • Save JerryNixon/915faf1e0aed75b61d1c7048c0fc0322 to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/915faf1e0aed75b61d1c7048c0fc0322 to your computer and use it in GitHub Desktop.
Generic Repository using Entity Framework
using Library.Models;
using Library.EF;
namespace Abstractions
{
public interface IKeyedModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
public class GenericContext<T> : DbContext where T : class, IKeyedModel
{
public DbSet<T> Items { get; set; } = default!;
}
public interface IRepository<T> where T : class, IKeyedModel
{
public GenericContext<T> Context() => new GenericContext<T>();
public T Select(int id) => Context().Items.Single(x => x.Id == id);
public IQueryable<T> Select() => Context().Items;
public void Insert(T item)
{
var context = Context();
context.Items.Add(item);
context.SaveChanges();
}
public void Update(T item)
{
var context = Context();
context.Items.Attach(item);
context.SaveChanges();
}
public void Delete(int id)
{
var context = Context();
var item = context.Items.Single(x => x.Id == id);
context.Items.Remove(item);
context.SaveChanges();
}
}
}
namespace Models
{
[Table(name: "User")]
public class User : IKeyedModel
{
public int Id { get; set; }
public string Name { get; set; } = default!;
}
}
namespace App
{
public class UserRepository : IRepository<User> { /* empty */ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment