我知道標題並不是最大的,但這是我真正想要完成的。從實體框架動態查詢實體與主實體的關聯
我有一個細節視圖,表示實體1及其關聯。我正在捕獲鍵/值對中的屬性名稱和值。我目前正在使用反射來將實體屬性設置爲非關聯的相應值。我懷疑這是最有效的方法,但我一直無法找到使用表達式樹的更好方法。因此,現在我需要根據這些實體關聯的主鍵將Entity1的關聯設置爲它們對應的實體,並將它們稱爲Entity2-4。
當迭代Entity1的屬性時,我不知道如何爲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相關聯。
我的基本模型:
ENTITY1
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
您不應該需要任何反射來顯示網格中的數據。也許你最好展示你的實體模型(基本部分)和樣例輸出。一定會有一種更簡單的方式來實現你想要的。 – 2013-04-10 20:36:41
我可以幫助協會發現部分 - 但我第二個什麼Gert說 - 這是不太可能的,除非你真的有一個獨特的情況。 – NSGaga 2013-04-10 20:39:13
好吧,這是交易,我使用動態數據,並使用詳細信息視圖執行插入。但是我有需要在代碼中管理的屬性,所以我使用細節視圖來設置UI,我在DetailsView_ItemInserting事件中完成我的魔術,提交實體並在ItemInserting上調用Cancel,因爲我已經手動添加了實體。 – m4chine 2013-04-10 20:51:00