不是很主题,但我有类似的问题,这是我的解决方案(任何人都可以帮忙)
创建身份类:
public class Identity
{
public int Id { get; set; }
}
创建实体类:
public class Employee: Identity
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
}
存储库接口(也只能使用抽象类):
interface IRepository<T> where T: Identity
{
T GetById(int id);
ICollection<T> GetAll();
ICollection<T> GetAll(string where);
void Update(T entity);
void Insert(T entity);
bool Delete(T entity);
bool Delete(ICollection<T> entityes);
}
创建通用抽象类:
public abstract class AbstractRepository<T>: IRepository<T> where T : Identity
{
protected abstract string TableName { get; }
protected abstract T DataRowToModel(DataRow dr);
protected virtual ICollection<T> DataTableToCollection(DataTable dt)
{
if (dt == null)
{
return null;
}
return dt.AsEnumerable().Select(x => DataRowToModel(x)).ToList();
}
public virtual T GetById(int id)
{
var query = $"select * from {TableName} where id = {id}";
//the data access layer is implemented elsewhere
DataRow dr = DAL.SelectDataRow(query);
return DataRowToModel(dr);
}
public virtual void Delete(T entity)
{
if (entity.Id == 0 )
{
return;
}
var query = $"delete from {TableName} where id = {entity.Id}";
DAL.Query(query);
}
public virtual void Delete(ICollection<T> entityes)
{
var collectionId = IdentityCollectionToSqlIdFormat(entityes);
if (string.IsNullOrEmpty(collectionId))
{
return;
}
var query = $"delete from {TableName} where id in ({collectionId})";
DAL.Query(query);
}
public virtual ICollection<T> GetAll()
{
var query = $"select * from {TableName}";
DataTable dt = DAL.SelectDataTable(query);
return DataTableToCollection(dt);
}
public virtual ICollection<T> GetAll(string where)
{
var query = $"select * from {TableName} where {where}";
DataTable dt = DAL.SelectDataTable(query);
return DataTableToCollection(dt);
}
protected virtual string IdentityCollectionToSqlIdFormat(ICollection<T> collection)
{
var array = collection.Select(x => x.Id);
return string.Join(",", array);
}
public abstract bool Update(T entity);
public abstract bool Insert(T entity);
}
并实现 EmployeeRepository:
public class EmployeeRepository : AbstractRepository<Employe>
{
protected sealed override string TableName
{
get
{
return "dbo.Employees";
}
}
protected sealed override Employe DataRowToModel(DataRow dr)
{
if (dr == null)
{
return null;
}
return new Employe
{
Id = dr.Field<int>("id"),
Name = dr.Field<string>("name"),
Surname = dr.Field<string>("surname"),
Age = dr.Field<int>("age")
};
}
public override void Insert(Employe entity)
{
var query = $@"insert into {TableName} (name, surname, age)
values({entity.Name},{entity.Surname},{entity.Age})";
DAL.Query(query);
}
public override bool Update(Employe entity)
{
throw new NotImplementedException();
}
}
就这样。在代码中使用:
public class SomeService
{
public void SomeeMethod()
{
int employeeId = 10; // for example
EmployeeRepository repository = new EmployeeRepository();
Employee employee = repository.GetById(employeeId);
repository.Delete(employee);
//...
}
}