这应该更简单,微软,呵呵,不是吗?
public abstract class AbstractRepository<TContext> : IRepository
where TContext : DataServiceContext
{
protected TContext Context;
public void SaveOrUpdate<TEntity>(TEntity entity)
{
try
{
this.Context.UpdateObject(entity);
}
catch
{
try
{
this.Context.AddObject(this.ResolveEntitySet(typeof(TEntity)), entity);
}
catch
{
}
}
}
private string ResolveEntitySet(Type type)
{
var entitySetAttribute = (EntitySetAttribute)type.GetCustomAttributes(typeof(EntitySetAttribute), true).FirstOrDefault();
if (entitySetAttribute != null)
return entitySetAttribute.EntitySet;
return null;
}
}
答案 0 :(得分:1)
你在寻找更像这样的东西吗?
public class EfRepository<T> : IRepository<T> where T : class
{
public EfRepository(DbContext dbContext)
{
if(dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public virtual IQueryable<T> GetAll()
{
return DbSet;
}
public virtual T GetById(int id)
{
return DbSet.Find(id);
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
public virtual void Update(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(entity);
}
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
public virtual void Delete(int id)
{
var entity = GetById(id);
if (entity == null) return;
Delete(entity);
}
}