通用工作单元

编程入门 行业动态 更新时间:2024-10-27 20:34:43
本文介绍了通用工作单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经实现了EntityFramework模式以及存储库和工作单元.该实现类似于代码项目存储库示例,但是我需要对工作单元进行增强.

I have implemented EntityFramework pattern along with Repository and Unit Of Work. The implementation is similar to Code Project Repository Example, however I need an enhancement for the Unit Of Work.

工作单位

public class GenericUnitOfWork : IDisposable { // Initialization code public Dictionary<Type, object> repositories = new Dictionary<Type, object>(); public IRepository<T> Repository<T>() where T : class { if (repositories.Keys.Contains(typeof(T)) == true) { return repositories[typeof(T)] as IRepository<T> } IRepository<T> repo = new Repository<T>(entities); repositories.Add(typeof(T), repo); return repo; } // other methods }

上面的UoW是一个安静的概括,它始终以父级Repository类为目标.我有另一个实体,例如学生,它有自己的存储库,该存储库扩展了Repository类.学生特定的存储库具有方法"GetStudentMarks()".现在,我无法使用常规的Unit of Work类,因为它始终指向父存储库.

The above UoW is quiet generalized and it targets the parent Repository class always. I have another entity, for example student, which has its own repository extending the Repository class. The student specific repository has a method "GetStudentMarks()". Now I cannot use the general Unit Of Work class since it always points to the parent Repository.

如何实施通用工作单位来处理此类情况?预先感谢.

How to implement a general Unit Of Work to handle such situations? Thanks in advance.

推荐答案

您可以使类 GenericUnitOfWork 泛型,并指定实体和存储库类型:

You can make the class GenericUnitOfWork generics, specifying the entity and repository type:

public class GenericUnitOfWork<TRepo, TEntity> : IDisposable where TRepo : Repository<TEntity> { // Initialization code public Dictionary<Type, TRepo> repositories = new Dictionary<Type, TRepo>(); public TRepo Repository() { if (repositories.Keys.Contains(typeof(TEntity)) == true) { return repositories[typeof(TEntity)]; } TRepo repo = (TRepo)Activator.CreateInstance( typeof(TRepo), new object[] { /*put there parameters to pass*/ }); repositories.Add(typeof(TEntity), repo); return repo; } // other methods }

类似的事情应该起作用.

Something like this should works.

更多推荐

通用工作单元

本文发布于:2023-11-06 22:20:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564828.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!