在這裏,我們去在Asp.Net MVC最佳Repository模式:
Repository模式增加了一個應用程序的數據和域層之間的分離層。它還使得應用程序的數據訪問部分可以更好地測試。
數據庫廠(IDatabaseFactory.cs):
public interface IDatabaseFactory : IDisposable
{
Database_DBEntities Get();
}
數據庫工廠實現(DatabaseFactory.cs):
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private Database_DBEntities dataContext;
public Database_DBEntities Get()
{
return dataContext ?? (dataContext = new Database_DBEntities());
}
protected override void DisposeCore()
{
if (dataContext != null)
dataContext.Dispose();
}
}
基本接口(IRepository.cs) :
public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Detach(T entity);
void Delete(T entity);
T GetById(long Id);
T GetById(string Id);
T Get(Expression<Func<T, bool>> where);
IEnumerable<T> GetAll();
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
void Commit();
}
抽象類(Repository.cs):
public abstract class Repository<T> : IRepository<T> where T : class
{
private Database_DBEntities dataContext;
private readonly IDbSet<T> dbset;
protected Repository(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
/// <summary>
/// Property for the databasefactory instance
/// </summary>
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
/// <summary>
/// Property for the datacontext instance
/// </summary>
protected Database_DBEntities DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
/// <summary>
/// For adding entity
/// </summary>
/// <param name="entity"></param>
public virtual void Add(T entity)
{
try
{
dbset.Add(entity);
// dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Added;
int iresult = dataContext.SaveChanges();
}
catch (UpdateException ex)
{
}
catch (DbUpdateException ex) //DbContext
{
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// For updating entity
/// </summary>
/// <param name="entity"></param>
public virtual void Update(T entity)
{
try
{
// dbset.Attach(entity);
dbset.Add(entity);
dataContext.Entry(entity).State = EntityState.Modified;
int iresult = dataContext.SaveChanges();
}
catch (UpdateException ex)
{
throw new ApplicationException(Database_ResourceFile.DuplicateMessage, ex);
}
catch (DbUpdateException ex) //DbContext
{
throw new ApplicationException(Database_ResourceFile.DuplicateMessage, ex);
}
catch (Exception ex) {
throw ex;
}
}
/// <summary>
/// for deleting entity with class
/// </summary>
/// <param name="entity"></param>
public virtual void Delete(T entity)
{
dbset.Remove(entity);
int iresult = dataContext.SaveChanges();
}
//To commit save changes
public void Commit()
{
//still needs modification accordingly
DataContext.SaveChanges();
}
/// <summary>
/// Fetches values as per the int64 id value
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual T GetById(long id)
{
return dbset.Find(id);
}
/// <summary>
/// Fetches values as per the string id input
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual T GetById(string id)
{
return dbset.Find(id);
}
/// <summary>
/// fetches all the records
/// </summary>
/// <returns></returns>
public virtual IEnumerable<T> GetAll()
{
return dbset.AsNoTracking().ToList();
}
/// <summary>
/// Fetches records as per the predicate condition
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
/// <summary>
///
/// </summary>
/// <param name="entity"></param>
public void Detach(T entity)
{
dataContext.Entry(entity).State = EntityState.Detached;
}
/// <summary>
/// fetches single records as per the predicate condition
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public T Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).FirstOrDefault<T>();
}
}
現在主要的問題是如何訪問控制器該存儲庫模式在這裏,我們去:
1.有用戶型號:
public partial class User
{
public int Id { get; set; }
public string Name { get; set; }
}
2.現在你必須創建你的usermodel的倉儲類
public class UserRepository : Repository<User>, IUserRepository
{
private Database_DBEntities dataContext;
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
public UserRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
DatabaseFactory = databaseFactory;
}
protected Database_DBEntities DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public interface IUserRepository : IRepository<User>
{
}
}
3.現在你必須創建UserService接口(IUserService.cs)所有的CRUD方法:
public interface IUserService
{
#region User Details
List<User> GetAllUsers();
int SaveUserDetails(User Usermodel);
int UpdateUserDetails(User Usermodel);
int DeleteUserDetails(int Id);
#endregion
}
4.現在您必須創建包含所有CRUD方法的UserService接口(UserService.cs):
public class UserService : IUserService
{
IUserRepository _userRepository;
public UserService() { }
public UserService(IUserRepository userRepository)
{
this._userRepository = userRepository;
}
public List<User> GetAllUsers()
{
try
{
IEnumerable<User> liUser = _userRepository.GetAll();
return liUser.ToList();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Saves the User details.
/// </summary>
/// <param name="User">The deptmodel.</param>
/// <returns></returns>
public int SaveUserDetails(User Usermodel)
{
try
{
if (Usermodel != null)
{
_userRepository.Add(Usermodel);
return 1;
}
else
return 0;
}
catch
{
throw;
}
}
/// <summary>
/// Updates the User details.
/// </summary>
/// <param name="User">The deptmodel.</param>
/// <returns></returns>
public int UpdateUserDetails(User Usermodel)
{
try
{
if (Usermodel != null)
{
_userRepository.Update(Usermodel);
return 1;
}
else
return 0;
}
catch
{
throw;
}
}
/// <summary>
/// Deletes the User details.
/// </summary>
/// <param name="Id">The code identifier.</param>
/// <returns></returns>
public int DeleteUserDetails(int Id)
{
try
{
User Usermodel = _userRepository.GetById(Id);
if (Usermodel != null)
{
_userRepository.Delete(Usermodel);
return 1;
}
else
return 0;
}
catch
{
throw;
}
}
}
5。現在大家的Repository模式設定時,你可以在用戶控制器訪問所有數據:
//Here is the User Controller
public class UserProfileController : Controller
{
IUserService _userservice;
public CustomerProfileController(IUserService userservice)
{
this._userservice = userservice;
}
[HttpPost]
public ActionResult GetAllUsers(int id)
{
User objUser=new User();
objUser = _userservice.GetAllUsers().Where(x => x.Id == id).FirstOrDefault();
}
}
乾杯!
我想說2號鏈接不是典型的存儲庫模式。通常情況下,您有[DDD](http://en.wikipedia.org/wiki/Domain-driven_design)中每個集合根的存儲庫。這是一個很好的[SO線程](http://stackoverflow.com/questions/1958621/whats-an-aggregate-root)關於這個話題。正如你所提到的,第二個例子似乎只是包裝一張桌子。看起來他們正在實施這種模式,只是爲了實現這種模式而沒有真正的好處。所以我會同意你的看法。 – RobertMS
你可能是對的。但是,在搜索網頁時,我發現大多數示例爲每個實體創建了單獨的包裝,包括我擁有的一些書中的包裝。在這方面,我發佈的鏈接上的代碼看起來很典型。感謝您的鏈接。我會檢查他們。 –
@JonathanWood這是[我最喜歡的解決方案](http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/)(該死的,我用這個鏈接很多)。即,具有通用方法的非通用知識庫接口。它仍然是'DbContext'上的一個相對較薄的包裝,但它允許更簡單的測試。 –