111*_*110 6 c# ado.net data-access-layer sqldatareader
我将尽力以最好的方式解释我的情景.我的数据库中有以下表格:
Products{ProductId, CategoryId ...}
Categories{CategoryId ...}
CategoryProperties{CategoryPropertyId, CategoryId, Name ...}
PropertyValues{ProductId, CategoryPropertyId, Value ...}
Run Code Online (Sandbox Code Playgroud)
因此,目标是拥有属于某个类别的产品列表,每个类别可以在"PropertyValues"表中包含具有值的"n"个属性.我有一个基于'categoryId'返回数据的查询,所以我总能从数据库中得到不同的结果:
对于CPU类别:
intel i7 | CPU | Model | Socket | L1 Cash | L2 Cahs | etc.
Run Code Online (Sandbox Code Playgroud)
对于HDD类别:
samsung F3 | HDD | Model | Speed | GB | etc.
Run Code Online (Sandbox Code Playgroud)
因此,根据我的查询中的类别,我总是可以得到不同的列号和名称.对于数据库访问,我使用简单的ADO.NET调用返回结果的存储过程.但是因为查询结果本质上是动态的,所以我不知道读取这些数据的好方法是什么.
我做了一个Product实体,但我很困惑如何使其真正:(
我认为我可以做一个Product实体,使该其他实体继承 Product一样Cpu,Hdd,Camera,PcCase,GraphicCard,MobilePhone,Gps等
,但我认为这是愚蠢的,因为我可以结束这与域中有200多个实体.
在这种情况下你会做什么?
如何阅读和放置这个动态属性?
更新 - 一些解决方案
可以根据@millimoose建议Dictionary和@Tim Schmelter想法使用DataTable对象我来到一些解决方案.
现在...这个工程,我得到的数据看他们,我可以显示出来.
但我仍然需要更聪明的人的意见比我在上午我做了这个好或者我应该更好地处理这种或者我做了一些spageti代码.所以在这里我做了什么:
public class Product
{
public Product()
{
this.DynamicProperties = new List<Dictionary<string, string>>();
}
public List<Dictionary<string, string>> DynamicProperties { get; set; }
}
...
List<Product> products = new List<Product>();
...
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataTable t = new DataTable();
a.Fill(t);
Product p = null;
foreach (DataRow row in t.Rows)
{
p = new Product();
foreach (DataColumn col in t.Columns)
{
string property = col.ColumnName.ToString();
string propertyValue = row[col.ColumnName].ToString();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add(property, propertyValue);
p.DynamicProperties.Add(dictionary);
}
products.Add(p);
}
}
Run Code Online (Sandbox Code Playgroud)
您有一个产品、一堆类别,每个类别都有一堆属性。
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; }
}
Run Code Online (Sandbox Code Playgroud)
您可以将产品属性存储在列表/字典中
然后您只需向产品添加属性
Properties.Add(new ProductionProperty() { Name="intel i7"});
Run Code Online (Sandbox Code Playgroud)
或者如果它的名称/值
Properties.Add(new ProductionProperty() { Name="Speed", Value="150MB/s"});
Run Code Online (Sandbox Code Playgroud)