C# C实体框架和存储库模式

C# C实体框架和存储库模式,c#,entity-framework,repository-pattern,C#,Entity Framework,Repository Pattern,使用工作单元和存储库模式,我有以下几点: public interface IDatabaseFactory<C> : IDisposable { C Get(); void Set(string connectionString); } public interface IUnitOfWork<C> { ICustomerRepository Customers { get; } //etc... void Commit();

使用工作单元和存储库模式,我有以下几点:

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;
    }
}
我的应用程序有一个db上下文,该上下文用于使用相同上下文的不同数据库。当用户登录系统时,他可以选择一个数据库,这将相应地设置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
必须在数据对象中实现的接口 您也可以在PK中使用其他then int:

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
您将要处理的查询结果是可扩展的

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 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

考虑不同的方法,使用通用存储库不一定是一个好方法,请参见域驱动的设计和我的应用程序有一个DB上下文,你的意思是你不在你的应用程序生命周期中处理一次你的上下文吗?这不是一个聪明的主意。有没有想过不使用这些?问题明确地说是C,这是VB.NET。。。我知道它们是相关的,但仍然如此。@anaximander:我知道问题是c,但我愿意分享我的代码。Juts不会努力把这个翻译成c。如果答案不正确,我会删除它。始终是一个有用的工具
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