我应该使用实体框架5通用存储库? [英] Should I be using a Generic Repository with Entity Framework 5?

查看:148
本文介绍了我应该使用实体框架5通用存储库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用实体框架与通用库和单位工作模式。我的模型是类似于在这篇文章

I'm currently using Entity Framework with a Generic Repository and Unit Of Work Pattern. My Model is similar to the one described in this article

我使用通用库在过去和真的很享受全球功能可以提供。但是,似乎我遇到了更多的问题,每一天,当涉及到使用它与实体框架。这些问题似乎当涉及到处理家长/孩子/结关系,以产生更大。

I've used Generic Repositories in the past and really enjoyed the global functionality it can provide. However, it seems I'm running into more problems every single day when it comes to using it with Entity Framework. These problems seem to arise even more when it comes to handling Parent/Children/Junction relationships.

使用通用存储库EF开始留下不好的味道在我的口,我开始觉得使用通用存储库EF是错误的做法

Using a Generic Repository with EF is starting to leave a bad taste in my mouth, and I'm beginning to think that using a Generic Repository with EF is the wrong approach.

可能有人请帮助引导我在正确的方向?

Could someone please help steer me in the right direction?

推荐答案

本文的方法是真的东西,可以成为一种痛苦,因为你已经有一个通用的存储库,并在EF通用IUnitOfWork和创建每种类型的特定库只是删除了通用的利益!

The approach of this article is really something that can be become a pain, because you already have a generic repository and a generic IUnitOfWork in EF and creating the specific repository for each type just removes the benefit of the generic!

我张贴在这里我怎么有一个通用的存储库和我IUnitOfWork,样品用这个你可以有一个非常好的库!

I am posting here a sample of how i have a generic Repository and my IUnitOfWork, with this you can have a very nice repository!

public interface IUnitOfWork : IDisposable
{
    void Save();
    void Save(SaveOptions saveOptions);
}

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    IUnitOfWork Session { get; }
    IList<TEntity> GetAll();
    IList<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate);
    bool Add(TEntity entity);
    bool Delete(TEntity entity);
    bool Update(TEntity entity);
    bool IsValid(TEntity entity);
}

和实施是这样的:

public class Repository : Component, IRepository
{

    protected DbContext session;

    public virtual IUnitOfWork Session
    {
        get
        {
            if (session == null)
                throw new InvalidOperationException("A session IUnitOfWork do repositório não está instanciada.");
            return (session as IUnitOfWork);
        }
    }

    public virtual DbContext Context
    {
        get
        {
            return session;
        }
    }

    public Repository(IUnitOfWork instance)
    {
        SetSession(instance);
    }

    public IList<TEntity> GetAll<TEntity>() where TEntity : class
    {
        return session.Set<TEntity>().ToList();
    }

    public IList<TEntity> GetAll<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return session.Set<TEntity>().Where(predicate).ToList();
    }

    public bool Add<TEntity>(TEntity entity) where TEntity : class
    {
        if (!IsValid(entity))
            return false;
        try
        {
            session.Set(typeof(TEntity)).Add(entity);
            return session.Entry(entity).GetValidationResult().IsValid;
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
                throw new Exception(ex.InnerException.Message, ex);
            throw new Exception(ex.Message, ex);
        }
    }

    public bool Delete<TEntity>(TEntity entity) where TEntity : class
    {
        if (!IsValid(entity))
            return false;
        try
        {
            session.Set(typeof(TEntity)).Remove(entity);
            return session.Entry(entity).GetValidationResult().IsValid;
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
                throw new Exception(ex.InnerException.Message, ex);
            throw new Exception(ex.Message, ex);
        }
    }

    public bool Update<TEntity>(TEntity entity) where TEntity : class
    {
        if (!IsValid(entity))
            return false;
        try
        {
            session.Set(typeof(TEntity)).Attach(entity);
            session.Entry(entity).State = EntityState.Modified;
            return session.Entry(entity).GetValidationResult().IsValid;
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
                throw new Exception(ex.InnerException.Message, ex);
            throw new Exception(ex.Message, ex);
        }
    }

    public virtual bool IsValid<TEntity>(TEntity value) where TEntity : class
    {
        if (value == null)
            throw new ArgumentNullException("A entidade não pode ser nula.");
        return true;
    }

    public void SetSession(IUnitOfWork session)
    {
        SetUnitOfWork(session);
    }

    protected internal void SetUnitOfWork(IUnitOfWork session)
    {
        if (!(session is DbContext))
            throw new ArgumentException("A instância IUnitOfWork deve um DbContext.");
        SetDbContext(session as DbContext);
    }

    protected internal void SetDbContext(DbContext session)
    {
        if (session == null)
            throw new ArgumentNullException("DbContext: instance");
        if (!(session is IUnitOfWork))
            throw new ArgumentException("A instância DbContext deve implementar a interface IUnitOfWork.");
        this.session = session;
    }

}

这篇关于我应该使用实体框架5通用存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆