I am looking for some help or pointers explaining a bit more on generating the whole Data Access Layer with a T4 Template. For example all the INSERT etc. statements and C# methods implementing it.
Asked
Active
Viewed 459 times
-1
-
1Why you are Generating Data Access Layer. @Marco Munnik – Mr doubt Sep 21 '16 at 10:30
-
1Any reason you don't want to use EF? Then you don't need this, or the repository pattern because EF is already implementing repository pattern/unit of work. – L-Four Sep 21 '16 at 13:31
1 Answers
1
You should not do that, try the Generic Repository pattern instead, you will end up with a single interface with a single implementation using Generics which can be used for any type in your model.
public interface IRepository<T, K> where T : class
{
T Add(T item);
bool Update(T item);
bool DeleteById(K id);
}
Implementation
public class EFRepository<T, K> : IRepository<T, K>, IDisposable where T : class
{
protected readonly DbContext _dbContext;
private readonly DbSet<T> _entitySet;
public EFRepository(DbContext context)
{
_dbContext = context;
_entitySet = _dbContext.Set<T>();
}
public T Add(T item)
{
item = _entitySet.Add(item);
_dbContext.SaveChanges();
return item;
}
public bool Update(T item)
{
_entitySet.Attach(item);
_dbContext.Entry(item).State = EntityState.Modified;
_dbContext.SaveChanges();
return true;
}
public bool DeleteById(K id)
{
var item = _entitySet.Find(id);
_entitySet.Remove(item);
_dbContext.SaveChanges();
return true;
}
}

Haitham Shaddad
- 4,336
- 2
- 14
- 19
-
1Wrapping EF with a "repository" structure like this is useless. The functionality is already provided by `DbSet` and `DbContext`. – user247702 Sep 21 '16 at 13:30
-
2@Haitham Shaddad I will use the same words: "you should not do that'. http://rob.conery.io/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/ – L-Four Sep 21 '16 at 14:03
-
2@Stijn The functionality exist in DbSet but you can't use it directly in your domain service or UI layer, also if you want to remove EntityFramework and use another data access layer, then it will not be possible without major refactorying – Haitham Shaddad Sep 22 '16 at 19:30