此 IRepository class 签名的用途
Purpose of this IRepository class signature
我正在尝试遵循描述的存储库模式 here。
谁能解释一下这到底意味着什么,它有什么好处?
<TEntity> where TEntity : class, IEntity
类 签名的一部分
public interface IRepository<TEntity> where TEntity : class, IEntity
{
TEntity Get(int id);
int Save(TEntity entity);
void Delete(TEntity entity);
}
我在 IRepository 的实施中没有看到任何明显的效果:
public class AppUserRepository : Repository, IRepository<AppUser>
{
public void Delete(AppUser entity)
{
using ( var context = new SourceEntities())
{
context.AppUsers.Attach(entity);
context.AppUsers.Remove(entity);
context.SaveChanges();
}
}
public AppUser Get(int id)
{
using (var context = new SourceEntities())
{
return context.AppUsers.Where(x => x.Id == id).SingleOrDefault();
}
}
public int Save(AppUser entity)
{
using (var context = new SourceEntities())
{
if ( entity.Id == 0 )
{
// this is a new record
context.AppUsers.Add(entity);
}
else
{
// existing record
context.AppUsers.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
// save the record
context.SaveChanges();
return entity.Id;
}
}
}
我认为您质疑 IEntity
interface
的目的是正确的。如果你问我,仅仅因为其他人这样做就是货物崇拜。
添加 interface
s,只是为了抽象的目的,增加了多余的复杂性。问自己一个问题:您是否会在代码中 use IEntity
而不关心实际处理的是什么类型?如果没有,我想不要抽象那部分。如果你这样做,为什么不呢?
通过查看您的代码,您的 Repository
正在做什么是非常清楚的。不要仅仅为了这样做而改变它。
如需进一步阅读,请参阅此 blog post。
更新
IMO,如果您的存储库需要 "GetById" 的能力,这可能是支持此类接口的理由。另一方面,为什么不实现接受表达式来搜索实体的 Find
方法?
一般来说,我更喜欢为一般目的实现抽象存储库,为某些特定需求实现派生存储库类。
我正在尝试遵循描述的存储库模式 here。
谁能解释一下这到底意味着什么,它有什么好处?
<TEntity> where TEntity : class, IEntity
类 签名的一部分
public interface IRepository<TEntity> where TEntity : class, IEntity
{
TEntity Get(int id);
int Save(TEntity entity);
void Delete(TEntity entity);
}
我在 IRepository 的实施中没有看到任何明显的效果:
public class AppUserRepository : Repository, IRepository<AppUser>
{
public void Delete(AppUser entity)
{
using ( var context = new SourceEntities())
{
context.AppUsers.Attach(entity);
context.AppUsers.Remove(entity);
context.SaveChanges();
}
}
public AppUser Get(int id)
{
using (var context = new SourceEntities())
{
return context.AppUsers.Where(x => x.Id == id).SingleOrDefault();
}
}
public int Save(AppUser entity)
{
using (var context = new SourceEntities())
{
if ( entity.Id == 0 )
{
// this is a new record
context.AppUsers.Add(entity);
}
else
{
// existing record
context.AppUsers.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
// save the record
context.SaveChanges();
return entity.Id;
}
}
}
我认为您质疑 IEntity
interface
的目的是正确的。如果你问我,仅仅因为其他人这样做就是货物崇拜。
添加 interface
s,只是为了抽象的目的,增加了多余的复杂性。问自己一个问题:您是否会在代码中 use IEntity
而不关心实际处理的是什么类型?如果没有,我想不要抽象那部分。如果你这样做,为什么不呢?
通过查看您的代码,您的 Repository
正在做什么是非常清楚的。不要仅仅为了这样做而改变它。
如需进一步阅读,请参阅此 blog post。
更新
IMO,如果您的存储库需要 "GetById" 的能力,这可能是支持此类接口的理由。另一方面,为什么不实现接受表达式来搜索实体的 Find
方法?
一般来说,我更喜欢为一般目的实现抽象存储库,为某些特定需求实现派生存储库类。