【发布时间】:2016-06-20 16:23:37
【问题描述】:
我在我的数据库中有一对多的关系我正在尝试使用通用方法更新集合中的所有对象。
public static void DuplicateItem<T>(T dataBaseItem, T origionalItem)
{
var type = origionalItem.GetType();
var properties = type.GetProperties();
var databasePropertyInfo = dataBaseItem.GetType();
foreach (var origionalProperty in properties)
{
var n = origionalProperty.Name;
var databaseProperty = databasePropertyInfo.GetProperty(origionalProperty.Name);
if(IsComplex(origionalProperty.GetValue(origionalItem,null)))
continue;
var origionalValue = origionalProperty.GetValue(origionalItem, null);
var t = Nullable.GetUnderlyingType(origionalProperty.PropertyType)
?? origionalProperty.PropertyType;
var saveValue = (origionalValue == null) ? null : Convert.ChangeType(origionalValue, t);
databaseProperty.SetValue(dataBaseItem, saveValue);
}
}
除了在集合上之外,此方法效果很好。它只会简单地将originalItem.Collection 中的项目添加到databaseItem.Colletion,这导致我拥有的项目数量是我应该拥有的项目数量的两倍,这让我通过了这个例外。我想要的只是将所有孩子从databaseItem.Collection 更新为origanalItem.Collection。
所以我试图做出改变:
public static void DuplicateItem<T>(T dataBaseItem, T origionalItem)
{
var type = origionalItem.GetType();
var properties = type.GetProperties();
var databasePropertyInfo = dataBaseItem.GetType();
foreach (var origionalProperty in properties)
{
var n = origionalProperty.Name;
var databaseProperty = databasePropertyInfo.GetProperty(origionalProperty.Name);
if(IsComplex(origionalProperty.GetValue(origionalItem,null)))
continue;
if (IsCollection(origionalProperty.GetValue(origionalItem, null)))
{
ClearItems(databaseProperty.GetValue(dataBaseItem,null),
origionalProperty.GetValue(origionalItem, null));
}
var origionalValue = origionalProperty.GetValue(origionalItem, null);
var t = Nullable.GetUnderlyingType(origionalProperty.PropertyType)
?? origionalProperty.PropertyType;
var saveValue = (origionalValue == null) ? null : Convert.ChangeType(origionalValue, t);
databaseProperty.SetValue(dataBaseItem, saveValue);
}
}
和 ClearItems:
private static void ClearItems(object databaseValue, object newvalue)
{
var l = databaseValue as IEnumerable<object>;
var n = newvalue as IEnumerable<object>;
if (l != null)
{
for (int i = 0; i < l.Count(); i++)
{
var dItem = l.ToList()[i];
var nItem = n.ToList()[i];
DuplicateItem(dItem,nItem);
}
}
}
这现在只给了我 3 个项目,但我仍然抛出异常。
所以现在我的问题:
如何使用ClearItems<TDatabase,TOriganial> 更新集合中的所有项目和集合中的所有属性?
谢谢。
【问题讨论】:
标签: c# generics entity-framework-6