Generic repository and pattern "Unit of work" for Entity framework
- .Net Framework 4.6.1
- EntityFramework 6.1.3
- Generic Repository
- Basic operation
- Add
- Add range
- Get list
- Get list with condition
- Get by id
- Get with condition
- Update
- Delete
- Support generic identity
- Asynchronous operation
- Add async
- Add range async
- Get list async
- Get list with condition async
- Get by id async
- Get with condition async
- Update async
- Delete async
- Hooks Supports
- Nested object save changes
- Soft delete
- Auto system infomation
- Audit log
- Global query filter
- Basic operation
- Unit of work
-
Install nuget package
Install-Package KirkChen.EFRepository
-
Create data class with interface IEntity
public class MyData : IEntity<int> { [Key] public int Id { get; set; } public string Content { get; set; } }
-
Create dbContext
public class MyDbContext: DbContext { public DbSet<MyData> MyDatas { get; set; } }
-
Create repository for data class
public class MyDataRepository : GenericRepository<int, MyData>, IRepository<int, MyData> { public MyDataRepository(MyDbContext context) : base(context) { // Enable soft delete this.RegisterPostLoadHook(new SoftDeletePostLoadHook<MyData>()); this.RegisterPostActionHook(new SoftDeletePostActionHook<MyData>()); } }
-
Use reository
var dbContext = new MyDbContext(); var repository = new MyDataRepository(dbContext); var myData = repository.Get(1);
Using unit of work to handle transaction
using(var dbContext = new MyDbContext())
using(var unitOfWork = new UnitOfWork(dbContext))
{
var repository = new MyDataRepository(dbContext);
repository.Add(data);
var anotherRepository = new OtherDataRepository(dbContext);
repository.Add(anotherdata);
unitOfWork.SaveChanges();
}
- Generic Repository
- Basic operation
- Add
- Add range
- Get list
- Get list with condition
- Get by id
- Get with condition
- Update
- Delete
- Support generic identity
- Asynchronous operation
- Add async
- Add range async
- Get list async
- Get list with condition async
- Get by id async
- Get with condition async
- Update async
- Delete async
- Hooks Supports
- Nested object save changes
- Soft delete
- Auto system infomation
- Audit log
- Global query filter
- Basic operation
- Unit of work