2011-05-17 46 views
0

在我编写的应用程序中,我通过数据上下文的反射来构建接口。显示值不成问题,但通过反射创建项目集合和分配值不起作用。IList与反射的EntityCollection

这里是有问题的代码:

var listItemType = property.PropertyType.GetGenericArguments().First(); 
// See remark #1 
var listType = typeof(List<>).MakeGenericType(new[] { listItemType }); 
var assocItems = Activator.CreateInstance(listType) as IList; 
var listSelector = EditorPanel.FindControl(property.Name) as PropertyListBox; 
if (listSelector != null) 
{ 
    foreach (var selectedItem in listSelector.SelectedItems) 
    { 
     assocItems.Add(selectedListItem); 
    } 
} 
// See remark #2 
property.SetValue(itemToUpdate, assocItems, null); 

备注1:

我试图线更改为var listType = typeof(EntityCollection<>).MakeGenericType(new[] {listItemType});再投assocItems到IListSource。取而代之的assocItems.Add()我叫assocItems.GetList().Add(),但导致了InvalidOperationException

对象不能被添加到 EntityCollection或的EntityReference。 附加到 ObjectContext的对象不能被添加到与源 对象没有关联的 EntityCollection或EntityReference 。

注2:

在这里,我需要将IList转换为EntityCollection<T>莫名其妙。

+0

为什么这么复杂的代码?你想做什么?这一定是可能的,没有反思。 – 2011-05-17 21:08:07

+0

应用程序的想法是,只要实体框架程序集和数据库必须更改,UI将适应程序集和类型。因此,可以在具有不同升级数据模型的许多实例上使用同一个应用程序。 – Residuum 2011-05-18 09:27:31

回答

1

而不是准备一个列表并将其设置为实体集合可以调用每个项目的EntityCollection属性上的添加功能?如果您不知道T的类型是否适合投射,则可以使用反射来调用该方法。

0

R基蒂有正确的答案,但另一个问题出现了,因为不能只设置类型为EntityCollection的属性。以下是试图做同样事情的人的全部技巧:

var listItemType = property.PropertyType.GetGenericArguments().First(); 
var clearMethod = property.PropertyType.GetMethod("Clear"); 
var addMethod = property.PropertyType.GetMethod("Add"); 
var listSelector = EditorPanel.FindControl(property.Name) as PropertyListBox; 
if (listSelector != null) 
{ 
    clearMethod.Invoke(property.GetValue(itemToUpdate, null), null); 
    foreach (var selectedItem in listSelector.SelectedItems) 
    { 
     addMethod.Invoke(property.GetValue(itemToUpdate, null), new[] {selectedItem}); 
    } 
}