How to read dynamic properties from database

不羁岁月 提交于 2019-12-01 05:16:32

You have a product, a bunch of categories, and each category has a bunch of properties.

class Product
{
    public int Id { get; set; }
    public Category Category { get; set; }
    public List<ProductProperty> Properties { get; set; }
}

class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
}

class ProductProperty
{
   public  int Id { get; set; }
   public  string Name { get; set; }
   public string Value { get; set; }
}

you could store the product properties in a list / dictionary

then you just add properties to the product

Properties.Add(new ProductionProperty() { Name="intel i7"});

or if its name/value

Properties.Add(new ProductionProperty() { Name="Speed", Value="150MB/s"});
nawfal

Your original approach

public class Product
{
    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,

public class Product
{
    public List<dynamic> DynamicProperties { get; set; }
}

...

conn.Open();
using (var reader = cmd.ExecuteReader())
{
    var p = new Products();
    p.DynamicProperties = reader.AsDyamic().ToList();

    //or

    foreach (var item in reader.AsDynamic())
        yield return item;
}

// carry this extension method around
public static 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];

        yield return expando;
    }
}

Somewhat related question: How to convert a data reader to dynamic query results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!