【问题标题】:How to create Dictionary containing the PK from tables如何从表中创建包含 PK 的字典
【发布时间】:2013-11-01 04:23:25
【问题描述】:
我想知道如何将表的主键与各自的值存储到字典中。
我的意思是,数据库中的一个表叫做 ContactPhone (PK = ID, ContactID, PhoneTypeID)
我想要类似的东西:
Dictionary<string, object>
字符串我的意思是表的主键,最终值将反映一个代表表的对象。当我的表有一个 PK 时,字典有一个字符串,最终是对象。但如果它是一个组合表,我需要保存许多 PK 来识别我的对象。执行此操作的最佳方法是什么。
【问题讨论】:
标签:
c#
dictionary
primary-key
business-objects
【解决方案1】:
这样做的一种方法是,声明一个ContactPhone 类型,然后使用它作为值添加到字典中
public class ContactPhone
{
public int ID {get; set);
public int ContactID {get; set;};
public int PhoneTypeID {get; set;};
}
// key is ID, value is the ContactPhone object
Dictionary<int, ContactPhone> contacts = new Dictionary<int, ContactPhone>();
// create a new ContactPhone object
ContactPhone contact = new ContactPhone(1, 1, 1);
// put the ContactPhone object into the dictionary with ID as the key
contacts.Add(1,contact);
当然,您必须获取数据,然后循环遍历它以将数据放入字典中。