0

我有一个带有 Delete 方法的抽象存储库类:

   public abstract class MyRepository<C, T> :
        IMyRepository<T>
        where T : class
        where C : ObjectContext, new()
    {
        private C _entities = new C();

        public C Context
        {
            get { return _entities; }
            set { _entities = value; }
        }

        public virtual void Delete(T entity)
        {
            _entities.Attach(entity);
            _entities.DeleteObject(entity);
            _entities.SaveChanges();
        }
    }

但是这不编译?如何在这里创建通用删除方法?

4

2 回答 2

0

而不是这个

private C _entities = new C();

使用Activator.CreateInstance

private C _entities = Activator.CreateInstance<T>();
于 2012-08-24T06:48:07.233 回答
0

修改你的Delete方法如下

    public virtual void Delete(T entity)
    {
        _entities.CreateObjectSet<T>().Attach(entity);
        _entities.DeleteObject(entity);
        _entities.SaveChanges();
    }

    public virtual void Update(T entity)
    {
        _entities.CreateObjectSet<T>().Attach(entity);
        _entities.ObjectStateManager
            .ChangeObjectState(entity, System.Data.EntityState.Modified); 
        _entities.SaveChanges();
    }
于 2012-08-24T06:49:05.037 回答