- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
使用工作单元和存储库模式,我有以下内容:
public interface IDatabaseFactory<C> : IDisposable
{
C Get();
void Set(string connectionString);
}
public interface IUnitOfWork<C>
{
ICustomerRepository Customers { get; }
//etc...
void Commit();
void ChangeDatabase(string connectionString);
string GetConnectionString(Database database);
}
public interface ICustomerRepository : IRepository<Customer> { }
和实现:
public class CustomerRepository : Repository<MyDbContext, Customer>, ICustomerRepository
{
public CustomerRepository (IDatabaseFactory<MyDbContext> databaseFactory)
: base(databaseFactory) { }
}
public class UnitOfWork<C> : IUnitOfWork<C> where C : DbContext, IMyDbContext
{
private readonly IDatabaseFactory<C> databaseFactory;
private C dataContext;
public UnitOfWork(IDatabaseFactory<C> databaseFactory)
{
this.databaseFactory = databaseFactory;
}
private ICustomerRepository customerRepository;
public ICustomerRepository Customers
{
get { return customerRepository?? (customerRepository = new CustomerRepository((IDatabaseFactory<MyDbContext>)databaseFactory)); }
}
private void ClearRespositories()
{
customerRepository = null;
}
protected C DataContext
{
get { return dataContext ?? (dataContext = databaseFactory.Get()); }
}
public string GetConnectionString(Model.Database database)
{
}
public void ChangeDatabase(string connectionString)
{
}
public void Commit()
{
}
}
我的模型有不少于 250 个主要实体,使用上述模式,需要相同数量的存储库,并且每个实体都是工作类单元中的一个属性。
我典型的服务层类是:
public class CustomerService : BaseService, ICustomerService
{
private ICustomerRepository customerRepository;
public CustomerService(IUnitOfWork<MyDbContext> unitOfWork) : base(unitOfWork) { }
public override void ChangeDatabase(string connectionString)
{
base.ChangeDatabase(connectionString);
customerRepository = unitOfWork.Customers;
}
}
我的应用程序有一个数据库上下文,这个上下文用于不同的数据库(使用相同的上下文)。当用户登录系统时,他可以选择一个数据库,这将相应地设置 uow 类的数据上下文。
我已将存储库添加到 UoW 类,以便所有存储库都具有相同的 uow。
这是正确的方法还是有更好的方法?
最佳答案
您可以使用通用存储库模式。这可以通过非常具体的域查询进行扩展。然后,您的 DI 容器可以创建您需要的特定存储库,您可以针对所有数据类对其进行操作。
如果对代码有任何疑问,请随时提出。
我会给你我的 VB.net 代码,希望它有用:
这是您将要使用的界面。保存和检索您的类(它们必须从 IEntity 继承)
Public Interface IRepository
Function GetEntity(Of T As {EntityObject, IEntity})(id As Integer) As T
Function GetAll(Of T As {EntityObject, IEntity})() As IEnumerable(Of T)
Sub Add(Of T As {EntityObject, IEntity})(entity As T)
Sub Remove(Of T As EntityObject)(entity As T)
Sub Attach(Of T As EntityObject)(entity As T)
Sub Update(Of T As {EntityObject, IEntity})(entity As T)
Function ExecuteQuery(Of T As {EntityObject, IEntity})(query As IQuery(Of T)) As IQueryResult(Of T)
Function ExecuteQuery(Of T As {EntityObject, IEntity}, TResult)(query As IQuery(Of T, TResult)) As IQueryResult(Of TResult)
End Interface
您必须在数据对象中实现的接口(interface)您还可以使用 other then int 进行 PK:
Public Interface IEntity
Property Id As Int32
End Interface
IQuery 对象,针对您的数据的特定查询实现它:
Public Interface IQuery(Of T As {EntityObject, IEntity})
Function Execute(ByVal objectSet As ObjectSet(Of T)) As IQueryResult(Of T)
End Interface
Public Interface IQuery(Of T As {EntityObject, IEntity}, TResult)
Function Execute(ByVal objectSet As ObjectSet(Of T)) As IQueryResult(Of TResult)
End Interface
您将使用的 QueryResult,它是可扩展的
Public Interface IQueryResult(Of T)
Function UniqueResult() As T
Function List() As IEnumerable(Of T)
End Interface
Public Class LinqResult(Of T)
Implements IQueryResult(Of T)
Private ReadOnly _query As IQueryable(Of T)
Public Sub New(query As IQueryable(Of T))
_query = query
End Sub
Protected Overridable Function ExpandQuery(query As IQueryable(Of T)) As IQueryable(Of T)
Return query
End Function
Public Function UniqueResult() As T Implements IQueryResult(Of T).UniqueResult
Dim result = ExpandQuery(_query).SingleOrDefault()
If result Is Nothing Then
Throw New EntityNotFoundException(Of T)()
End If
Return result
End Function
Public Function List() As IEnumerable(Of T) Implements IQueryResult(Of T).List
Return ExpandQuery(_query).ToList()
End Function
End Class
您的 ObjectcontextRepository,您的 IRepository 的实际实现
Public Class EntityObjectContextRepository
Implements IRepository
Private ReadOnly Property _context As ObjectContext
Get
Return UnitOfWork.Current
End Get
End Property
Public Sub Add(Of T As {EntityObject, IEntity})(entity As T) Implements IRepository.Add
_context.CreateObjectSet(Of T)().AddObject(entity)
End Sub
Public Sub Attach(Of T As EntityObject)(entity As T) Implements IRepository.Attach
_context.Attach(entity)
'_context.CreateObjectSet(Of T)().Attach(entity)
End Sub
Public Sub Update(Of T As {EntityObject, IEntity})(ByVal entity As T) Implements IRepository.Update
_context.CreateObjectSet(Of T)().Attach(entity)
_context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified)
End Sub
Public Function ExecuteQuery(Of T As {EntityObject, IEntity})(query As IQuery(Of T)) As IQueryResult(Of T) Implements IRepository.ExecuteQuery
Return query.Execute(_context.CreateObjectSet(Of T))
End Function
Public Function ExecuteQuery(Of T As {EntityObject, IEntity}, TResult)(ByVal query As IQuery(Of T, TResult)) As IQueryResult(Of TResult) Implements IRepository.ExecuteQuery
Return query.Execute(_context.CreateObjectSet(Of T))
End Function
Public Function GetAll(Of T As {EntityObject, IEntity})() As IEnumerable(Of T) Implements IRepository.GetAll
Return _context.CreateObjectSet(Of T).ToList().Where(Function(c) c.EntityState <> EntityState.Deleted)
End Function
Public Function GetEntity(Of T As {EntityObject, IEntity})(id As Integer) As T Implements IRepository.GetEntity
Dim entity = _context.CreateObjectSet(Of T)().SingleOrDefault(Function(x) x.Id = id)
Return ReturnEntityWhenItExists(entity)
End Function
Public Sub Remove(Of T As EntityObject)(entity As T) Implements IRepository.Remove
_context.DeleteObject(entity)
End Sub
Private Function ReturnEntityWhenItExists(Of T As {EntityObject, IEntity})(ByVal entity As T) As T
If entity IsNot Nothing AndAlso entity.EntityState <> EntityState.Deleted Then
Return entity
End If
Throw New EntityNotFoundException(Of T)()
End Function
End Class
包装这一切的工作单元:
Public Class UnitOfWork
Implements IDisposable
Private Shared _dataContext As ObjectContext
Public Shared ReadOnly Property Current As ObjectContext
Get
If _dataContext Is Nothing Then
Throw New UnitOfWorkException(ResourceRetriever.GetResource(Of String)("ExceptionUnitOfWorkNotInitializedMessage"))
End If
Return _dataContext
End Get
End Property
Public Sub New()
Me.New(New YourDataModelContainer())
End Sub
Public Sub New(ByVal objectContext As ObjectContext)
If _dataContext IsNot Nothing Then
Throw New UnitOfWorkException(ResourceRetriever.GetResource(Of String)("ExceptionUnitOfWorkAlreadyInitializedMessage"))
End If
_dataContext = objectContext
End Sub
Public Sub Complete()
If _dataContext Is Nothing Then
Throw New UnitOfWorkException(ResourceRetriever.GetResource(Of String)("ExceptionUnitOfWorkNotInitializedMessage"))
End If
_dataContext.SaveChanges()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If _dataContext IsNot Nothing Then
_dataContext.Dispose()
_dataContext = Nothing
End If
End Sub
End Class
查询示例:
Public Class GetAllBuildingsQuery
Implements IQuery(Of DataAccess.Building, BuildingDto)
Public Function Execute(ByVal objectSet As ObjectSet(Of Building)) As IQueryResult(Of BuildingDto) Implements IQuery(Of Building, BuildingDto).Execute
Dim query = objectSet.Select(Function(g) New BuildingDto() With {.Description = g.Name, .Id = g.Id})
Return New LinqResult(Of BuildingDto)(query)
End Function
End Class
在服务调用中是如何实现的:
Public Class EmployeeService
Implements IEmployeeService
Private ReadOnly _repository As IRepository
Public Sub New(ByVal repository As IRepository)
_repository = repository
End Sub
Public Function GetAllEmployees() As IEnumerable(Of EmployeeOverviewDto) Implements IEmployeeService.GetAllEmployees
Dim employees = _repository.ExecuteQuery(EmployeeQueries.GetAllEmployeesForOverview()).List()
Return employees
End Function
End Class
关于C# Entity Framework 和存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22553375/
这个问题在这里已经有了答案: 10年前关闭。 Possible Duplicates: What is a framework? What does it do? Why do we need a f
我在按照 http://msdn.microsoft.com/en-us/data/jj591621.aspx 处的 Microsoft Data Developer 过程启用代码优先迁移时遇到了一些
我正在从 迁移项目 Entity Framework 4.3 在 .net 4 上运行到 Entity Framework 5 在 .net 4.5 上运行。在不做任何更改的情况下,当我尝试运行该项目
我正在使用 Entity Framework 6 并使用 EntityFramework Extended 来执行一些批量更新和批量删除。批量更新和批量删除工作正常,但我还需要知道更新/删除的实体(即
我在实体上添加了一个列,然后从模型中生成数据库或构建解决方案,然后收到一条消息,提示我刚添加的新列未映射。该数据库以前是从模型创建的,没有错误。 当我右键单击Entity并选择Table Mappin
每次我尝试运行我的代码时都会崩溃,因为我尝试启动函数以调用 SDK 的任何部分。 我在构建过程中包含了 FoundationSDK: 并且我在头文件中包含了对 SDK 的引用: 但是每次我运行这个,我
我以前能够毫无问题地提交我的申请。我的工作流程中唯一改变的部分是使用 Sourcetree。在对以下框架进行更新后,我在提交到 iOS App Store 时收到此警告。我还收到一封电子邮件,其中包含
假设我为 Asp.NET Web 应用程序安装了 .NET Framework 2.0、3.0、3.5。 我意识到 Framework 3.0 和 3.5 只是 Framework 2 的扩展,不太清
是否有 SaveChanges 事件在保存更改后但在更新更改跟踪器之前触发? 我正在使用 EF 6。 我需要在某个实体的状态发生变化时执行任务。 我已经覆盖了 SaveChanges 来设置它。我可以
我正在使用一个现有的数据库,并且我已经将其中一个表映射为一个实体(因为我需要映射一个外键)。 因此,在初始化此数据库时,我希望 EF 忽略此实体,因为它已经存在。 我该怎么做? 最佳答案 您应该使用
我有 3 个表需要与 Entity Framework 进行映射,但我不确定解决此问题的正确方法。这是我的 3 个实体: public class User { [Key] public
我首先使用 VS 2010 和 Entity Framework 代码(版本 6)。我有两个实体,每个实体都在自己的上下文中,我想在它们之间创建一对多关系。 上下文 1 具有以下实体: public
我知道 EF 在 CodePlex 上是开源的,但我没有看到当前发布的 5.0 版本的分支。我在哪里可以得到这个源代码? 最佳答案 没有。他们只开源了 post 5 版本。第一次签到可能足够接近,但再
我们目前有一个数据库很大的系统,存储过程既用于CUD又用于查询。数据集用于从 SP 查询中检索结果。 现在我们正在研究使用 Entity Framework 针对同一个数据库开发另一个项目。在查询数据
我有一个每 10 秒运行一次的 Windows 服务......每次运行时,它都会获取一些测试数据,对其进行修改并使用 EntityFramework 将其保存到数据库中。但是,在每一秒运行时,当我尝
我对在我们的场景中仅将 Entity Framework 与存储过程一起使用的合理性有疑问。 我们计划拥有一个 N 层架构,包括 UI、BusinessLayer (BLL)、DataAccessLa
当我使用 Entity Framework 时,我想在上下文中查询出一条记录并将其添加到具有相同架构的另一个上下文中,在查询出记录后,我将其从上下文中分离出来,但是相关实体都没有了,是吗?有什么办法解
我正在使用 Entity Framework 5 构建 ASP.Net MVC4 Web 应用程序。我必须使用现有的 sql server 数据库,但也想使用 Code First,所以我遵循了本教程
在 Entity Framework 4.0 中使用 T4 模板创建 POCO 会丢失什么?为什么使用 Entity Framework 4.0 时的默认行为不创建 POCO? 最佳答案 你会失去很多
我在网上使用 Repository Pattern 和 EF 看了很多例子。但他们都没有真正谈到与相关实体的合作。 就像说用户可以有多个地址。 IUserRepository User CreateU
我是一名优秀的程序员,十分优秀!