C# 具有通用存储库和工作单元的实体框架

C# 具有通用存储库和工作单元的实体框架,c#,asp.net-mvc,entity-framework,repository-pattern,unit-of-work,C#,Asp.net Mvc,Entity Framework,Repository Pattern,Unit Of Work,我正在我的一个应用程序中使用带有通用存储库的实体框架。我需要整合工作单元。我有点困惑,在不影响应用程序性能的情况下,用通用存储库模式添加工作单元的最佳方法是什么。有人能帮我做这件事吗 我已经添加了我的通用存储库代码和其他存储库代码,如下所示 通用存储库: using System; using System.Data.Entity; using System.Data.Entity.Validation; using System.Linq; using System.Threading.Tas

我正在我的一个应用程序中使用带有通用存储库的实体框架。我需要整合工作单元。我有点困惑,在不影响应用程序性能的情况下,用通用存储库模式添加工作单元的最佳方法是什么。有人能帮我做这件事吗

我已经添加了我的通用存储库代码和其他存储库代码,如下所示

通用存储库:

using System;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Threading.Tasks;
using EntityFrameworkDemo.Entity;
using EntityFrameworkDemo.Models;
using EntityFrameworkDemo.Repository.UnitOfWork;

namespace EntityFrameworkDemo.Repository
{
    public class BaseRepository<T> : IDisposable where T : BaseModel
    {
      internal EFContext db;

    public BaseRepository()
    {
        db = new EFContext();
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="BaseRepository"/> class.
    /// </summary>
    /// <param name="context">The context.</param>
    public BaseRepository(EFContext context)
    {
        db = context;
    }

    /// <summary>
    /// Gets this instance.
    /// </summary>
    /// <returns></returns>
    public IQueryable<T> GetAll()
    {
        return db.Set<T>().Where(t => !t.DeletedOn.HasValue);
    }



    /// <summary>
    /// Gets the specified identifier.
    /// </summary>
    /// <param name="id">The identifier.</param>
    /// <returns></returns>
    public T Get(long? id)
    {
        return db.Set<T>().Find(id); ;
    }

    /// <summary>
    /// Gets the specified identifier.
    /// </summary>
    /// <param name="id">The identifier.</param>
    /// <returns></returns>
    public Task<T> GetASync(long? id)
    {
        return db.Set<T>().FindAsync(id);
    }

    /// <summary>
    /// Inserts the specified current.
    /// </summary>
    /// <param name="current">The current.</param>
    /// <returns></returns>
    public async Task<T> Insert(T current)
    {
        db.Set<T>().Add(current);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }

        return await db.Set<T>().FirstAsync();
    }

    /// <summary>
    /// Inserts the specified current.
    /// </summary>
    /// <param name="current">The current.</param>
    /// <returns></returns>
    public async Task Update(T current)
    {
        db.Entry<T>(current).State = System.Data.Entity.EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the f  ollowing validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }

    }

    /// <summary>
    /// Deletes the specified identifier.
    /// </summary>
    /// <param name="id">The identifier.</param>
    /// <returns></returns>
    public async Task Delete(long? id)
    {
        var current = await this.GetASync(id);
        if (current != null)
        {
            current.DeletedOn = DateTime.Now;
            db.Entry<T>(current).State = System.Data.Entity.EntityState.Modified;
            await db.SaveChangesAsync();
        }
    }

    /// <summary>
    /// Deletes the specified identifier permanently.
    /// </summary>
    /// <param name="id">The identifier.</param>
    /// <returns></returns>
    public async Task DeletePermanently(long? id)
    {
        var current = await this.GetASync(id);
        if (current != null)
        {
            db.Set<T>().Remove(current);
            await db.SaveChangesAsync();
        }
    }

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Finalizes an instance of the <see cref="BaseRepository"/> class.
    /// </summary>
    ~BaseRepository()
    {
        Dispose(false);
    }

    /// <summary>
    /// Releases unmanaged and - optionally - managed resources.
    /// </summary>
    /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (db != null)
            {
                db.Dispose();
                db = null;
            }
        }
    }
}
使用系统;
使用System.Data.Entity;
使用System.Data.Entity.Validation;
使用System.Linq;
使用System.Threading.Tasks;
使用EntityFrameworkEmo.Entity;
使用EntityFrameworkEmo.Models;
使用EntityFrameworkEmo.Repository.UnitOfWork;
命名空间EntityFrameworkDemo.Repository
{
公共类BaseRepository:IDisposable其中T:BaseModel
{
内部环境数据库;
公共基本存储库()
{
db=新的EFContext();
}
/// 
///初始化类的新实例。
/// 
///上下文。
公共BaseRepository(EFContext上下文)
{
db=上下文;
}
/// 
///获取此实例。
/// 
/// 
公共IQueryable GetAll()
{
返回db.Set().Where(t=>!t.DeletedOn.HasValue);
}
/// 
///获取指定的标识符。
/// 
///标识符。
/// 
公共无法获取(长?id)
{
返回db.Set().Find(id);
}
/// 
///获取指定的标识符。
/// 
///标识符。
/// 
公共任务GetASync(长?id)
{
返回db.Set().FindAsync(id);
}
/// 
///插入指定的电流。
/// 
///电流。
/// 
公共异步任务插入(T当前)
{
db.Set().Add(当前);
尝试
{
等待db.saveChangesSync();
}
捕获(DbEntityValidationException e)
{
foreach(e.EntityValidationErrors中的变量eve)
{
WriteLine(“状态为“{1}\”的类型为“{0}\”的实体”存在以下验证错误:“,
eve.Entry.Entity.GetType().Name,eve.Entry.State);
foreach(eve.ValidationErrors中的变量ve)
{
Console.WriteLine(“-Property:\“{0}\”,错误:\“{1}\”,
ve.PropertyName,ve.ErrorMessage);
}
}
投掷;
}
返回wait db.Set().FirstAsync();
}
/// 
///插入指定的电流。
/// 
///电流。
/// 
公共异步任务更新(T当前)
{
db.Entry(current.State=System.Data.Entity.EntityState.Modified;
尝试
{
等待db.saveChangesSync();
}
捕获(DbEntityValidationException e)
{
foreach(e.EntityValidationErrors中的变量eve)
{
WriteLine(“状态为“{1}\”的类型为“{0}\”的实体”具有以下验证错误:“,
eve.Entry.Entity.GetType().Name,eve.Entry.State);
foreach(eve.ValidationErrors中的变量ve)
{
Console.WriteLine(“-Property:\“{0}\”,错误:\“{1}\”,
ve.PropertyName,ve.ErrorMessage);
}
}
投掷;
}
}
/// 
///删除指定的标识符。
/// 
///标识符。
/// 
公共异步任务删除(长?id)
{
var current=wait this.GetASync(id);
如果(当前!=null)
{
current.DeletedOn=DateTime.Now;
db.Entry(current.State=System.Data.Entity.EntityState.Modified;
等待db.saveChangesSync();
}
}
/// 
///永久删除指定的标识符。
/// 
///标识符。
/// 
公共异步任务永久删除(长?id)
{
var current=wait this.GetASync(id);
如果(当前!=null)
{
db.Set().Remove(当前);
等待db.saveChangesSync();
}
}
/// 
///执行与释放、释放或重置非托管资源相关的应用程序定义的任务。
/// 
公共空间处置()
{
处置(真实);
总干事(本);
}
/// 
///完成类的实例。
/// 
~BaseRepository()
{
处置(虚假);
}
/// 
///释放非托管和(可选)托管资源。
/// 
///如果为true,则同时释放托管和非托管资源;如果为false,则仅释放非托管资源。
受保护的虚拟void Dispose(bool disposing)
{
如果(处置)
{
如果(db!=null)
{
db.Dispose();
db=null;
}
}
}
}
}

学生资料库:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFrameworkDemo.Models;

namespace EntityFrameworkDemo.Repository
{
    public class StudentRepository : BaseRepository<Student>
    {
    public StudentRepository()
        : base()
    { }

    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用EntityFrameworkEmo.Models;
命名空间EntityFrameworkDemo.Repository
{
公共类StudentRepository:BaseRepository
{
公共研究职位
:base()
{ }
}
}
控制器:

 public class HomeController : Controller
{
    private StudentRepository studentRepo = new StudentRepository();

    public async Task<ActionResult> Index()
    {
        var test = studentRepo.GetAll();

        return View();
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            studentRepo.Dispose();
        }
        base.Dispose(disposing);
    }
}
公共类HomeController:控制器
{
private StudentRepository studentRepo=新StudentRepository();
公共异步任务索引()
{
var test=studentRepo.GetAll();
返回视图();
}
受保护的覆盖无效处置(布尔处置)
{
如果(处置)
{
studentRepo.Dispose();
}
基地。处置(处置);
}
}

您可能想知道实体框架上下文是工作单元模式的实现(当您执行
context.SaveChanges()
时,您将执行工作单元)。因此,我非常确定,在90%的情况下,不需要对其进行额外的实现,除非您希望从具体的数据源/数据中抽象数据层
- lazy loading
- eager loading
- explicit loading