How To Read Dynamic Properties From Database
I will try to explain my scenario the best way I can. I have the following tables in my database: Products{ProductId, CategoryId ...} Categories{CategoryId ...} CategoryProperties{
Solution 1:
Your original approach
publicclassProduct
{
public List<Dictionary<string, string>> DynamicProperties { get; set; }
}
is quite good. I would use a custom collection though, with better naming so the intent is clearer.
You could also utilize C# 4.0's dynamic feature which more cool, but I'm not sure what benefit it gives in your case. You could do something like,
publicclassProduct{
publicList<dynamic> DynamicProperties { get; set; }
}
...
conn.Open();
using (var reader = cmd.ExecuteReader())
{
var p = new Products();
p.DynamicProperties = reader.AsDyamic().ToList();
//orforeach (var item in reader.AsDynamic())
yieldreturn item;
}
// carry this extension method aroundpublicstatic IEnumerable<dynamic> AsDynamic(this IDataReader reader)
{
var names = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
foreach (IDataRecord record in reader as IEnumerable)
{
var expando = new ExpandoObject() as IDictionary<string, object>;
foreach (var name in names)
expando[name] = record[name];
yieldreturn expando;
}
}
Somewhat related question: How to convert a data reader to dynamic query results
Solution 2:
You have a product, a bunch of categories, and each category has a bunch of properties.
classProduct
{
publicint Id { get; set; }
public Category Category { get; set; }
public List<ProductProperty> Properties { get; set; }
}
classCategory
{
publicint Id { get; set; }
publicstring Name { get; set; }
}
classProductProperty
{
publicint Id { get; set; }
publicstring Name { get; set; }
publicstring Value { get; set; }
}
you could store the product properties in a list / dictionary
then you just add properties to the product
Properties.Add(newProductionProperty() { Name="intel i7"});
or if its name/value
Properties.Add(newProductionProperty() { Name="Speed", Value="150MB/s"});
Post a Comment for "How To Read Dynamic Properties From Database"