【发布时间】:2013-04-10 20:28:11
【问题描述】:
我知道标题不是最棒的,但这是我真正想要完成的。
我有一个表示 Entity1 及其关联的详细信息视图。我正在捕获键/值对中的属性名称和值。我目前正在使用反射将实体属性设置为非关联的相应值。我怀疑这是最有效的方法,但我一直无法找到使用表达式树的更好方法。所以现在我需要根据这些实体关联的主键设置Entity1与其对应实体的关联,称它们为Entity2-4。
在迭代Entity1的Properties时,不知道如何构造一个对Entity2-4的动态查询,并将Entity1.association设置为对应的实体。这是我到目前为止的代码:
foreach (string k in e.Values.Keys)
{
if (e.Values[k] != null && !String.IsNullOrEmpty(e.Values[k].ToString()))
{
System.Type objectType = Entity1.GetType();
PropertyInfo[] p = objectType.GetProperties();
foreach (PropertyInfo pi in p)
{
// set Entity1.Property for non associations (works just fine)
if (pi.Name == k)
{
System.Type t = pi.PropertyType;
pi.SetProperty(e.Values[k].ToString(), Entity1);
break;
}
// when i see pi.Name contain Reference, I know I'm working on an association
else if (pi.Name.Contains("Reference"))
{
// k is in the form of Entity.Property
var name = pi.Name.Left("Reference");
var keys = k.Split('.');
var ent = keys[0];
var prop = keys[1];
if (name == ent)
{
// here I need to obtain an instance from the db
// ie generate my dynamic query to the Entity with the name
// contained within the var "ent"
// I tried using reflection and could instantiate the entity
// but it did me no good as I needed the entity from the db
var entityInstance = some dynamic query;
// here I need to set the association of Entity1 to entityInstance from above
// normally I would use reflection, but I'm not sure that would work
// since EntityReference is the actual property returned by reflection
Entity1.SetAssocation(prop, Entity2);
break;
}
}
}
}
}
编辑
我基本上需要构造实体及其关联实体,以便我可以将它们提交到数据上下文。实体 2 到 4 存在于数据库中,我需要查询数据库以获取实例,我可以将它们关联到我正在创建并要提交的新实体 1。
我的基本模型:
实体1
Entity1.ID
Entity1.Prop1
Entity1.Prop2
Entity1.Prop3
Entity1.Entity2
Entity1.Entity3
Entity1.Entity4
Entity2
Entity2.ID
Entity2.Name
Entity3
Entity3.ID
Entity3.Name
Entity4
Entity4.ID
Entity4.Name
【问题讨论】:
-
您根本不需要任何反射来在网格中显示数据。也许您最好展示您的实体模型(基本部分)和示例输出。一定有一种更简单的方法可以实现您想要的。
-
我可以在
associations discovery部分提供帮助 - 但我是第二个 Gert 所说的 - 这有点不太可能,除非你真的有一个独特的场景。 -
好的,这就是交易,我正在使用动态数据,并且正在使用详细信息视图来执行插入。但是我有需要在代码中管理的属性,所以我使用详细信息视图来设置 UI,我在 DetailsView_ItemInserting 事件中施展魔法,提交实体,然后在 ItemInserting 上调用 Cancel,因为我刚刚手动添加了实体。
-
展示我的实体模型的最佳方式是什么?
-
抱歉,它不是网格,而是详细信息视图,已修复错字。
标签: c# entity-framework reflection expression-trees dynamic-queries