【发布时间】:2011-08-17 03:39:36
【问题描述】:
我为ValueInjecter 创建了一个自定义注入类,它为通用子集合进行递归注入,但它适用于现有目标对象,而不是像 VI 站点上的“CloneInjection”示例那样进行克隆。但是,目前我正在转换为已知类型 (ICollection
//for value types and string just return the value as is
if (c.SourceProp.Type.IsValueType || c.SourceProp.Type == typeof(string))
return c.SourceProp.Value;
if (c.SourceProp.Type.IsGenericType)
{
//handle IEnumerable<> also ICollection<> IList<> List<>
if (c.SourceProp.Type.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
{
var t = c.TargetProp.Type.GetGenericArguments()[0];
if (t.IsValueType || t == typeof(string)) return c.SourceProp.Value;
//get enumerable object in target
var targetCollection = c.TargetProp.Value as ICollection<MyTargetType>;
//possible to cast dynamically?
foreach (var o in c.SourceProp.Value as IEnumerable)
{
//get ID of source object
var sourceID = (int)o.GetProps().GetByName("ID").GetValue(o);
//find matching target object if there is one
var target = targetCollection.SingleOrDefault(x => x.ID == sourceID);
if (target != null)
{
target.InjectFrom<RecursiveInjection>(o);
}
}
return targetCollection;
}
}
谢谢,丹奥
【问题讨论】:
-
你能告诉我你想达到什么目标吗?
-
@Omu - 看看我在 VI “深度克隆”页面上的帖子 - valueinjecter.codeplex.com/… - 我正在更新 EF POCO 实体,因此必须直接更新目标对象属性而不是创建克隆
-
我了解到您正在尝试执行类似克隆注入但没有克隆的操作,并且您成功使用
但您需要它更加动态(也许您也可以尝试制作一个通用的注入),我想知道的是为什么/正在尝试做什么,您的初始源和目标对象是什么以及您想从一个注入到另一个 -
@Omu - 我正在尝试创建一个可重用的注入,它将注入从 EF 上下文加载的 POCO 实体,其值来自通过 MVC 表单发布的类似视图模型对象,我希望注入递归处理所有子集合及其属性(例如,具有 Orders 子集合的 Customer 实体)。 Customer.Orders = CustomerViewModel.Orders 不适用于 EF,这就是克隆注入不起作用的原因。有意义吗?
-
这是可行的,但是集合存在问题,例如,如果在源端删除了集合中间的项目,您如何知道源集合中的哪个对象要注入目标集合的哪个对象,不能一一拿来认为它们的顺序相同,因为它们可能不是
标签: c# .net dynamic casting valueinjecter