如果您的实体类型并非都实现相同的接口或派生自相同的类,这将很困难。如果他们这样做,那很简单:
// example base type, which your entities would need to implement
public interface IApprovable
{
public int ID {get; set;}
public string Approved_by {get; set;}
public DateTime Approved_on {get; set;}
}
//...
public void ApproveRowTable<T>(List<int> idValues)
where T : IApprovable
{
using(var context = new SSPModel.sspEntities())
{
var table = context.Set<T>();
var entities = table.Where(e => idValues.Contains(e.ID));
foreach(var entity in entities)
{
entity.Approved_by = GlobalClass.GlobalVar;
entity.Approved_on = DateTime.Now;
}
context.SaveChanges();
}
}
如果您的实体类型没有实现通用的基本类型,那么您应该通过创建实现它的空部分来修改它们:
public partial class GeneralRule : IApprovable {}
如果您不能这样做,那么您可以执行以下操作。(我假设ID
是 PK,所以我们可以使用Find()
而不需要构建表达式:
public void ApproveTableRows(Type entityType, IEnumerable<int> idsToApprove)
{
using(var context = new SSPModel.sspEntities())
{
var set = context.Set(entityType);
if(set == null)
throw new ArgumentException("No DbSet found with provided name", "tableSetName");
var approveByProperty = entityType.GetProperty("Approved_by");
var approveOnProperty = entityType.GetProperty("Approved_on");
if(approveByProperty == null || approveOnProperty == null)
throw new InvalidOperationException("Entity type does not contain approval properties");
foreach (object id in idsToApprove)
{
var entityInstance = set.Find(id);
approveByProperty.SetValue(entityInstance, GlobalClass.GlobalVar);
approveOnProperty.SetValue(entityInstance, DateTime.Now);
}
context.SaveChanges();
}
}
如您所见,这效率较低,因为它为每个 ID 发出一个新查询,而不是一次获取所有 ID。此外,该方法接受实体Type
而不是字符串,以避免需要通过反射来寻找正确的属性。这可以改进,但实际上我认为您应该更新您的实体以实现共享接口。