给定任何实体Foo
,我通常创建名为CreateFooCommand
,UpdateFooCommand
和DeleteFooCommand
的命令。它们的结构都非常相似,所以我想知道在编写单独的代码生成脚本之外生成这些的最佳方法是什么。理想情况下,我更喜欢使用T4使用Roslyn解析现有结构并在此基础上生成-可行吗?
一种实现方法是将泛型与接口配合使用,以便您的目标类可以实现基本代码:
创建这样的基类:
public abstract class DataRepositoryBase<T, U> :
IDisposable,
IDataRepository<T>
where T : class, new()
where U : DbContext, new()
{
private U _context = null;
protected U Context
{
get { return _context; }
}
public DataRepositoryBase()
{
_context = new U();
_context.Configuration.AutoDetectChangesEnabled = false;
}
public T Add(T entity)
{
T result = AddEntity(Context, entity);
Context.SaveChanges();
SetState(result, EntityState.Detached);
return result;
}
public T Remove(T entity)
{
var result = RemoveEntity(Context, entity);
Context.SaveChanges();
SetState(entity, EntityState.Detached);
return result;
}
public T Update(T entity)
{
var result = UpdateEntity(Context, entity);
Context.SaveChanges();
SetState(entity, EntityState.Detached);
return result;
}
protected virtual T AddEntity(U context, T entity)
{
SetState(entity, EntityState.Added);
return entity;
}
protected virtual T RemoveEntity(U entityContext, T entity)
{
SetState(entity, EntityState.Modified);
return entity;
}
protected virtual T UpdateEntity(U context, T entity)
{
SetState(entity, EntityState.Modified);
return entity;
}
protected void SetState(T entity, EntityState state)
{
Context.Entry(entity).State = state;
}
}
然后每个类都有一个实现DataRepositoryBase的存储库:
public class FooRepository : DataRepositoryBase<Foo, YourDataContext> { }
因此您可以使用:
var fooRepository = new FooRepository().Add(foo);
此示例使用存储库模式,但是您可以将基类用于其他实现。