-
Notifications
You must be signed in to change notification settings - Fork 0
/
EfEntityRepositoryBase.cs
62 lines (57 loc) · 1.81 KB
/
EfEntityRepositoryBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using Core.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Core.DataAccess.EntityFramework
{
public class EfEntityRepositoryBase<TEntity, TContext> : IEntityRepository<TEntity>
where TEntity : class, IEntity, new()
where TContext : DbContext, new()
{
public void Add(TEntity entity)
{
using (TContext context = new TContext())
{
var addedCar = context.Entry(entity);
addedCar.State = EntityState.Added;
context.SaveChanges();
}
}
public void Delete(TEntity entity)
{
using (TContext context = new TContext())
{
var deletedCar = context.Entry(entity);
deletedCar.State = EntityState.Deleted;
context.SaveChanges();
}
}
public TEntity Get(Expression<Func<TEntity, bool>> filter)
{
using (TContext context = new TContext())
{
return context.Set<TEntity>().FirstOrDefault(filter);
}
}
public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null)
{
using (TContext context = new TContext())
{
return filter == null
? context.Set<TEntity>().ToList()
: context.Set<TEntity>().Where(filter).ToList();
}
}
public void Update(TEntity entity)
{
using (TContext context = new TContext())
{
var updatedCar = context.Entry(entity);
updatedCar.State = EntityState.Modified;
context.SaveChanges();
}
}
}
}