我试图通过
使用EF仅从表中提取某些列dynamic var = new ExpandoObject.
最终目标是允许用户选择他们想要从API返回的字段,并使代码仅提取那些列。
我的问题是,假设根据他们的数据有100条记录,我的动态对象是一个引用,因此当我更新一个列表项时,它们都会被更新。
代码:
dynamic expando = new ExpandoObject();
var output = new List<ExpandoObject>();
PopulateDynamicObject(expando); // adds the columns the user had marked to include
static dynamic PopulateDynamicObject(dynamic rootObject)
{
var fields = GetLeadFields();
foreach (var field in fields)
{
AddProperty(rootObject, field.FieldName, "");
}
return rootObject;
}
// get data from database. snip
// List all fields possible but UpdateProperty will only update properties which exist, therefore it honours PopulateDynamicObject
UpdateProperty(expando, "LeadId", dbLead.leadID);
UpdateProperty(expando, "CompanyId", dbLead.companyID);
UpdateProperty(expando, "CompanyName", dbLead.company);
UpdateProperty(expando, "UnitIdentity", dbLead.unitIdentity);
UpdateProperty(expando, "BadgeId", dbLead.badgeID);
UpdateProperty(expando, "ScanDate", dbLead.scanDate);
UpdateProperty(expando, "FirstName", dbLead.firstName);
UpdateProperty(expando, "LastName", dbLead.lastName);
UpdateProperty(expando, "Company", dbLead.company);
UpdateProperty(expando, "Address1", dbLead.address1);
UpdateProperty(expando, "Address2", dbLead.address2);
UpdateProperty(expando, "Address3", dbLead.address3);
static void UpdateProperty(ExpandoObject expando, string propertyName, object propertyValue = null)
{
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
}
但是最终结果是n行都具有相同的数据。