-
Notifications
You must be signed in to change notification settings - Fork 0
/
EfEntityRepositoryBase.cs
71 lines (65 loc) · 2.08 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
63
64
65
66
67
68
69
70
71
using Core.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
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 addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
context.SaveChanges();
}
}
public void Delete(TEntity entity)
{
using (TContext context = new TContext())
{
var deletedEntity = context.Entry(entity);
deletedEntity.State = EntityState.Deleted;
context.SaveChanges();
}
}
public TEntity Get(Expression<Func<TEntity, bool>> filter)
{
using (TContext context = new TContext())
{
return context.Set<TEntity>().SingleOrDefault(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 updatedEntity = context.Entry(entity);
updatedEntity.State = EntityState.Modified;
context.SaveChanges();
}
}
public bool Exists(Expression<Func<TEntity, bool>> filter)
{
using (TContext contex = new TContext())
{
return contex.Set<TEntity>().Any<TEntity>(filter);
}
}
}
}