What could be the better implementation for STE, I heard about that DbContext is the simplest way to implement a Repo with EF, personally I take advantage of the EntityState, but there is any member on ObjectContext that could deliver more functionallity for my CRUD operations using Repo? at today I'm using a GenericRepository like this one :
public class GenericRepository<TEntity> where TEntity : class
{
internal DbContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
}
I forgot to mention that also I'm using Unity, so the calls to Repository are like this way :
[Dependency]
public IUnityContainer Container { get; set; }
public List<Case> GetAll()
{
using (var context = Container.Resolve<ClaimEntities>())
{
var qry = (from c in context.Cases
select c).ToList();
return qry;
}
}
Interface implemented by objects that can provide an ObjectContext instance. The DbContext class implements this interface to provide access to the underlying ObjectContext.
DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table.
You can use a DbContext associated to a model to: Write and execute queries. Materialize query results as entity objects. Track changes that are made to those objects.
Self tracking entities are feature of ObjectContext - they are not supported in DbContext. If you want STEs you need to swap to ObjectContext API and use STEs T4 template to generate entities instead of your current POCOs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With