gpt4 book ai didi

c# - Entity Framework 6、存储库模式和工作单元

转载 作者:行者123 更新时间:2023-11-30 20:46:26 25 4
gpt4 key购买 nike

<分区>

我正在学习 Entity Framework 和一些设计模式,例如存储库模式和工作单元。我编写了一个使用这些模式的程序。在这个类中,我有一个 DbContext 对象,我总是使用这个静态 DbContext。在我的应用程序的整个生命周期中,只有一个 DbContext 对象。我这样做对吗,想想如果有很多用户。关于数据库连接的任何问题。

界面代码:

UnitOfWork uow = GetUnitOfWork(); //There is only one uow object
uow.EmployeeRepository.Insert(new Employee
{
Name = name,
Surname = surname
});

GetUnitOfWork 代码:

private static UnitOfWork _uow;
public static UnitOfWork GetUnitOfWork()
{
return _uow ?? (_uow = new UnitOfWork());
}

工作单元代码:

public class UnitOfWork : IDisposable
{
private static FollowerEntities _context;
private DbContextTransaction _transaction;

//repositories
private EmployeeRepository _employeeRepository;


public UnitOfWork()
{
_context = new FollowerEntities();
}

public EmployeeRepository EmployeeRepository
{
get { return _employeeRepository ?? (_employeeRepository = new EmployeeRepository(_context)); }
}

public void Save()
{
try
{
_transaction = _context.Database.BeginTransaction();
_context.SaveChanges();
_transaction.Commit();
}
catch
{
_transaction.Rollback();
throw;
}
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
}

员工资料库

public class EmployeeRepository : GenericRepository<Employee>
{
public EmployeeRepository(FollowerEntities entities)
: base(entities)
{

}
}

通用存储库

public class GenericRepository<T> where T : class
{
private FollowerEntities _entities;


private DbSet<T> table = null;

public GenericRepository()
{

}

public GenericRepository(FollowerEntities entities)
{
this._entities = entities;
table = _entities.Set<T>();
}

public IEnumerable<T> SelectAll()
{
return table.ToList();
}

public T SelvectById(object id)
{
return table.Find(id);
}

public void Insert(T obj)
{
table.Add(obj);
}

public void Update(T obj)
{
table.Attach(obj);
_entities.Entry(obj).State = EntityState.Modified;
}

public void Delete(object id)
{
T existing = table.Find(id);
table.Remove(existing);
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com