在我编写的应用程序中,我通过数据上下文的反射来构建接口。显示值不成问题,但通过反射创建项目集合和分配值不起作用。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>
莫名其妙。
为什么这么复杂的代码?你想做什么?这一定是可能的,没有反思。 – 2011-05-17 21:08:07
应用程序的想法是,只要实体框架程序集和数据库必须更改,UI将适应程序集和类型。因此,可以在具有不同升级数据模型的许多实例上使用同一个应用程序。 – Residuum 2011-05-18 09:27:31