我在我的EntityFramework支持的存储库中有一个reoccuring代码块,我想以某种方式进行泛化并调用方法,因此重用代码而不是重复它.
当前代码块如下所示:
// Archive deleted MyItems sections
_t.MyItems.Where(x => x.ValidTo == null && !team.MyItems.Contains(x)).ToList().ForEach(x => x.ValidTo = DateTime.Now);
// Add or update MyItems sections
foreach (var MyItemsSection in team.MyItems)
{
if (MyItemsSection.Id == default(int))
{
MyItemsSection.ValidFrom = DateTime.Now;
_t.MyItems.Add(MyItemsSection);
}
else
{
var _MyItemsSection = _t.MyItems.FirstOrDefault(x => x.Id == MyItemsSection.Id);
context.Entry(_MyItemsSection).CurrentValues.SetValues(MyItemsSection);
}
}
_t是EntityFramework连接的对象图,而团队是一种相同类型的对象图,它已被断开并可能在外部更新.这里的目标是同步两个对象图,以便保持更改.
我需要传入_t.MyItems和team.MyItems,其中MyItems将被通用化,因此相同的方法适用于MyOtherItems和MySocks,MyUnderPants等.
这是可能吗?
最佳答案 您有两种选择:将对象约束为已知的基本类型,该类型包含要在泛型方法中访问的属性和方法,或者使用谓词进行选择.
约束:
// base type
interface IFoo {
int ID { get; set; }
}
// generic method
public List<T> Update<T>(List<T> graph1, List<T> graph2) where T : IFoo {
var update = graph1.Intersect(graph2, (g1, g2) => { g1.ID == g2.ID }).ToList();
return update;
}
谓词:
public void Update<T, U>(T _t, T team, Func<T, IList<U>> selector)
{
var _tItems = selector(_t);
var teamItems = selector(team);
// Archive deleted MyItems sections
_tItems.Where(x => x.ValidTo == null && !teamItems.Contains(x)).ToList().ForEach(x => x.ValidTo = DateTime.Now);
// Add or update MyItems sections
foreach (var MyItemsSection in teamItems)
{
if (MyItemsSection.Id == default(int))
{
MyItemsSection.ValidFrom = DateTime.Now;
_tItems.Add(MyItemsSection);
}
else
{
var _MyItemsSection = _tItems.FirstOrDefault(x => x.Id == MyItemsSection.Id);
context.Entry(_MyItemsSection).CurrentValues.SetValues(MyItemsSection);
}
}
}
//Usage:
Update(_t, team, (t => t.MyItems));
但话又说回来,是什么阻止你编写一个以列表为参数的方法呢?
如公共无效更新< T>(IList< T> _tItems,IList< T> teamItems)