Bon*_*ney 3 c# asp.net-mvc entity-framework repository-pattern
我第一次尝试在 MVC 应用程序中使用工作单元模式,该应用程序已经遵循实体框架 DbContext 的存储库模式。我的问题是关于调用 Savechanges() 方法的最佳位置/实践。
我看到了两种可能的方法:
对于第一种方法,我们必须对注入到 Controller 中的 UnitOfWork 实例调用 SaveChanges()。对于第二种方法,SaveChanges() 将封装在 Repository 中,Controller 需要做的就是调用 Repository 中的方法(由 UnitOfWork 提供),并且将在 Repository 中调用 SaveChanges()。
方法一:
public class PostsController : Controller
{
private readonly IRepository<Post> _postRepository;
private readonly IRepository<Category> _categoryRepository;
private readonly IUnitOfWork _uow;
public PostsController(IUnitOfWork uow)
{
if (uow == null)
throw new ArgumentNullException(nameof(uow));
_uow = uow;
_postRepository = uow.Repository<Post>();
_categoryRepository = uow.Repository<Category>();
}
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
_postRepository.Add(post);
_uow.SaveChanges();
}
return View(post);
}
}
public class UnitOfWork : IUnitOfWork
{
private CodingSoldierDbContext _dbContext;
private Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
public UnitOfWork(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException(nameof(dbContext));
_dbContext = dbContext as CodingSoldierDbContext;
}
public IRepository<T> Repository<T>() where T : class
{
if (_repositories.Keys.Contains(typeof(T)))
{
return _repositories[typeof(T)] as IRepository<T>;
}
IRepository<T> repository = new Repository<T>(_dbContext);
_repositories.Add(typeof(T), repository);
return repository;
}
public void SaveChanges()
{
_dbContext.SaveChanges();
}
}
public class Repository<T> : IRepository<T> where T : class
{
CodingSoldierDbContext _dbContext;
public Repository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException(nameof(dbContext));
_dbContext = dbContext as CodingSoldierDbContext;
}
public void Add(T item)
{
_dbContext.Set<T>().Add(item);
//_dbContext.SaveChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
方法 2: 不添加代码,因此问题仍然很短。在方法 1 中,在 Controller 的 Create 方法中,删除该行:
_uow.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
从 UnitOfWork 中删除“SaveChanges”方法定义。
取消注释存储库类中的注释行:
_dbContext.SaveChanges()
Run Code Online (Sandbox Code Playgroud)
我觉得第二种方法比第一种方法更好,因为控制器中的代码更清晰,并且 SaveChanges 是直接与 DbContext 交互的同一个类(存储库)的责任。
任何人,如果您有任何理由我们应该遵循第一种方法,请告诉我?
我更喜欢在 UnitOfWork 上下文中实现 SaveChanges,因为如果您编辑来自多个存储库的多个实体,您不想在每个存储库上执行保存更改。
例子:
var unitOfWork = UnitOfWorkFactory.Create();
var categoryRepo = unitOfWork.GetRepository<Category>();
var postRepo= unitOfWork.GetRepository<Post>();
var cat = new Category("name");
categoryRepo.Add(cat);
var post = new Post("Title", "Message");
post.Category = cat;
postRepo.Add(post );
unitOfWork.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
保存完整的上下文(在一次转换中)更容易。
| 归档时间: |
|
| 查看次数: |
4777 次 |
| 最近记录: |