我已经实现了 EntityFramework 模式以及存储库和工作单元。实现类似于代码项目存储库示例 http://www.codeproject.com/Articles/770156/Understanding-Repository-and-Unit-of-Work-Pattern?msg=5295955#xx5295955xx,但是我需要对工作单元进行增强。
工作单位
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 类为目标。我有另一个实体,例如学生,它有自己的存储库,扩展了存储库类。学生特定存储库有一个方法“GetStudentMarks()”。现在我无法使用通用工作单元类,因为它始终指向父存储库。
如何实现通用工作单元来处理这种情况?提前致谢。
通用工作单元!!!
您实施了错误的工作单元
请参阅此代码:
using System.Data.Entity;
using System;
namespace EF_Sample07.DataLayer.Context
{
public interface IUnitOfWork
{
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
}
为什么使用工作单元?
Because:
参见示例:
Category
public class Category
{
public int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Title { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Product
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
}
工作单元
public interface IUnitOfWork
{
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
数据库上下文
public class Sample07Context : DbContext, IUnitOfWork
{
public DbSet<Category> Categories { set; get; }
public DbSet<Product> Products { set; get; }
#region IUnitOfWork Members
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
public int SaveAllChanges()
{
return base.SaveChanges();
}
#endregion
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)