Reputation: 39
I would like to know how to dynamically add an undetermined number of unmapped properties to an entity. We are currently using a DataTable and dynamically adding columns and then binding that table to an UltraGrid; I would like to replicate that with an entity. Please note that I am using the N-Tier Entity Framework (https://ntieref.codeplex.com/).
I could either dynamically create an entity with properties, or dynamically add properties to an existing entity that does not contain any mapped properties. Each time the application runs, a different number of properties will be added, so I don’t need to permanently retain new/dynamic properties. I want to be able to bind the EntitySet as a datasource for an UltraGrid; I will not be utilizing this entity for data modification directly, only accessing the state tracking.
I found a DynamicPropertyHelper class in the N-Tier Entity Framework library but am unable to determine what it is used for.
My entities already inherit from another class and thus cannot inherit from ExpandoObject.
Here are some related posts but I don’t think they are the answer(s) I’m looking for.
Dynamically add new property with any name to object
I would like to think that entities have at least as much functionality as datasets…
I would appreciate any assistance, even if the answer is that it can’t be done.
Thank you.
Upvotes: 2
Views: 1792
Reputation: 337
You can allow entities to support dynamic properties by overriding the protected methods GetDynamicValue
and SetDynamicValue
.
It’s up to you how values of dynamic properties are stored and exposed through the WCF data contract. However, you can use DynamicPropertyHelper
to do this job. The helper uses binary serialization and base-64 encoding to store all dynamic properties as an XML string. Here is a sample:
partial class MyEntity
{
[DataMember]
[SimpleProperty]
private string DynamicContent
{
get { return _dynamicContent; }
set
{
if (_dynamicContent != value)
{
OnPropertyChanging("DynamicContent", value);
var previousValue = _dynamicContent;
_dynamicContent = value;
OnPropertyChanged("DynamicContent", previousValue, value);
}
}
}
private string _dynamicContent;
protected override object GetDynamicValue(string propertyName)
{
return DynamicPropertyHelper.GetDynamicProperty(DynamicContent, propertyName);
}
protected override void SetDynamicValue(string propertyName, object value)
{
var dynamicContent = DynamicContent;
DynamicPropertyHelper.SetDynamicProperty(ref dynamicContent, propertyName, value);
DynamicContent = dynamicContent;
}
}
You can then simply set and get dynamic property values via the entity’s indexer:
MyEntity x = ...;
x[“DynamicPropertyName”] = dynamicPropertyValue;
Upvotes: 1