c# - 带有 EntityFramework 的通用存储库

标签 c# entity-framework repository-pattern

我想使用 Entity Framework 实现一个通用的存储库模式(我知道关于存储库有很多有争议的观点,但这仍然是我所需要的)。 我希望它具有的界面如下:

public interface IRepository
{
    IQueryable<TEntity> Query<TEntity>() 
        where TEntity: Entity;

    void Save<TEntity>(TEntity entity) 
        where TEntity : Entity;

    void Delete<TEntity>(TEntity entity) 
        where TEntity : Entity;
}

Entity 是一个只有 int ID 属性的基类。 并像这样使用它:

        IRepository repository = ... // get repository (connects to DB)
        int userId = GetCurrentUserId();
        if (!repository.Query<User>().Any(u => u.Id == userId)) // performs SELECT query
        {    /*return error*/    }

        var newOrder = new Order { UserId = userId, Status = "New" }
        repository.Save(newOrder); // performs INSERT query
        ...
        newOrder.Status = "Completed";
        repository.Save(newOrder); // performs UPDATE query

我想避免使用 UnitOwWork 并在 Save()Delete() 被调用后将所有对象更改提交到数据库.我想做的事情看起来很简单,但我还没有找到任何如何使用 EntityFramework 来做的例子。我能找到的最接近的例子是 this answer ,但它使用 UnitOwWork 和 repository-per-entity,这比我需要做的更复杂。

最佳答案

1-创建一个界面

interface IMain<T> where T : class
    {
        List<T> GetAll();
        T GetById(int id);
        void Add(T entity);
        void Edit(T entity);
        void Del(int id);
        int Savechange();
    }

2-创建一个类

public class Main<T> : IMain<T> where T : class
    {
        public DataContext db;
        public void Add(T entity)
        {
            db.Set<T>().Add(entity);
        }

        public void Del(int id)
        {
            var q = GetById(id);
            db.Set<T>().Remove(q);
        }

        public void Edit(T entity)
        {
            db.Entry<T>(entity).State = EntityState.Modified;
        }

        public List<T> GetAll()
        {
            return db.Set<T>().Select(a=>a).ToList();
        }

        public T GetById(int id)
        {
            return db.Set<T>().Find(id);
        }

        public int Savechange()
        {
            return db.SaveChanges();
        }
    }

3-创建一个名为 YourTable ForExample Student

的存储库
 public class Student : Main<Tbl_Student>
    {
        public Student()
        {
            db = new DataContext();
        }
    }

4-根据您的操作编写此代码

Student student=new Student();
student.Del(3);
int a = student.Savechange();

关于c# - 带有 EntityFramework 的通用存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42831048/

相关文章:

c# - 实例类的静态成员

C# - 关闭 - 澄清

c# - WPF 表单与后台线程锁定

c# - 在 C++ 中为同一公式获取与在 C# 中不同的值

c# - 关于模拟 EF 5 和测试存储库模式的一些问题

unit-testing - Microsoft 的 Entity Framework 如何抑制测试驱动开发?

c# - Entity Framework 5 - 无法加载文件或程序集 EntityFramework,版本 = 5.0.0.0

php - 存储库模式和共享实体

C# 如何将 Expression<Func<SomeType>> 转换为 Expression<Func<OtherType>>

node.js - NodeJS : how to implement repository pattern