0

这应该更简单,微软,嗯,不是吗?

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;
    }
}
4

1 回答 1

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);
        }
    }
于 2013-02-09T19:28:00.983 回答