【问题标题】:Generate Data Access Layer with t4 template使用 t4 模板生成数据访问层
【发布时间】:2017-01-29 13:11:37
【问题描述】:

我正在寻找一些帮助或指针来解释更多关于使用 T4 模板生成整个数据访问层的信息。例如所有 INSERT 等语句和实现它的 C# 方法。

【问题讨论】:

  • 为什么要生成数据访问层。 @Marco Munnik
  • 有什么理由不想使用 EF?那么你不需要这个,或者存储库模式,因为 EF 已经在实现存储库模式/工作单元。

标签: c# .net t4 data-access-layer


【解决方案1】:

您不应该这样做,而是尝试使用 Generic Repository 模式,您最终会得到一个使用泛型实现的单一接口,该接口可用于您模型中的任何类型。

public interface IRepository<T, K> where T : class
    {
        T Add(T item);
        bool Update(T item);
        bool DeleteById(K id);
    }

实施

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

【讨论】:

  • 用这样的“存储库”结构包装 EF 是没有用的。该功能已由DbSetDbContext 提供。
  • @Haitham Shaddad 我会用同样的话:“你不应该那样做”。rob.conery.io/2014/03/04/…
  • @Stijn 该功能存在于 DbSet 中,但您不能直接在域服务或 UI 层中使用它,如果您想删除 EntityFramework 并使用另一个数据访问层,则不会无需重大重构即可实现
猜你喜欢
  • 1970-01-01
  • 2013-10-03
  • 2011-10-28
  • 2011-07-03
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2011-05-31
相关资源
最近更新 更多