我目前正在研究ASP.NET MVC 5项目,并且正在尝试完善该项目的体系结构。使它尽可能干净,方便人们将来使用。
首先,我将EntityFramework模型(包括IdentityUser和AccountViewModel)移到同一解决方案中的Class库项目中。目前,主要的MVC项目已引用了这一点。
但是,我现在正在考虑创建一个新的数据访问层项目,该项目将保存DbContext(或DbContext,如果我决定使用多个DbContext),以及数据访问层。进行此操作的最佳方法是什么?
该DAL项目将引用Model项目,而主MVC项目将仅引用DAL项目。
看完这篇文章!我想知道使用EntityFramework时是否确实过时了存储库模式。
所以我的两个主要问题是:
1)将DAL导出到单独项目中的最佳方法是什么
2)什么是使用EF访问数据库内容的最佳方法
您的问题很广泛。例如,“使用EF访问数据库内容的最佳方法”是什么意思?在性能方面最好的方法?
我将尝试通过给出一个我更喜欢的选项(我主要使用一些变体)来回答,该选项使用存储库模式。如果您将EF集直接用作存储库,您可能会认为您不需要存储库模式,但是我想将它们包装在自己的存储库中。
由于我无法通过最佳方式理解您的意思,因此我将给出适合于典型Web项目的个人偏好。
我不会发布所有代码以使其完全起作用,但是您应该对所发生的事情有个清楚的了解。
设置(4个项目):
UI ----------> Domain.Logic(带有Domain.Models)----------------->数据(保留EF上下文)。
数据:
public partial class EFContextContainer : DbContext
enter code here
public EFContextContainer ()
: base("name=EFContextContainer")
{
}
public DbSet<IdentityUser> IdentityUsers { get;set; }
使用包装器返回上下文:
public static class Database
{
public static EFContextContainerGetContext()
{
return new EFContextContainer();
}
}
您可能具有如下的存储库设置:
接口:
public interface IRepository<T> where T : class
{
IQueryable<T> GetAll();
T GetById(Guid id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Guid id);
}
实现(为简洁起见,仅实现了Add(T实体)):
public class EFRepository<T> : IRepository<T>, IDisposable where T : class
{
public EFRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
public void Dispose()
{
DbContext.Dispose();
}
}
域:
Domain.Logic(IdentityUserManager将是Domain.Models中的类):
public class IdentityUserManager
{
public void Add(IdentityUser idUser)
{
using(var idUserRepository = new EFRepository<IdentityUser>(Database.GetContext())
{
idUserRepository.Add(idUser);
}
}
}
用户界面:
[HttpPost]
public ActionResult Post(UserViewModel model)
{
UserIdentity user = MapUser(model);
var userManager = new IdentityUserManager();
userManager.Add(user);
return View(new UserViewModel());
}
(这不是在Visual Studio中全部组成的,因此可以避免任何拼写错误。)
诚然,此代码中可以包含更多抽象,但是在此处写下整个解决方案是荒谬的。例如,您也可以使用工作单元模式,该模式与存储库模式一起使用非常好。因此,请阅读此示例,而不是有关如何实施此设置的完整指南。可以设置比本示例干净得多的东西。
为了深入了解其中一些模式的实现,我敦促您浏览John Papa在Plural Sight上开设的Single Page Apps课程。他出色地解释了这些模式的好处以及如何实现它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句