例子见上一篇即可,说说使用DataReader的心得,在做项目中,有时候一个实体类中的字段又是另外一个实体雷,存在外键的关系。如下实体类源码 中就有2个这样的关系(高亮代码):
using System; using System.Collections.Generic; using System.Text; namespace BookShop.Model { [Serializable] public class Book { /// /// 图书编号 /// private int id; public int Id { get { return id; } set { id = value; } } /// /// 图书标题 /// private string title; public string Title { get { return title; } set { title = value; } } /// /// 图书作者 /// private string author; public string Author { get { return author; } set { author = value; } } /// /// 图书出版社 /// private Publisher publisher; public Publisher Publisher { get { return publisher; } set { publisher = value; } } /// /// 图书出版日期 /// private DateTime publishDate; public DateTime PublishDate { get { return publishDate; } set { publishDate = value; } } /// /// 图书ISBN编号 /// private string isbn; public string Isbn { get { return isbn; } set { isbn = value; } } /// /// 图书总字数 /// private int wordsCount; public int WordsCount { get { return wordsCount; } set { wordsCount = value; } } /// /// 图书价格 /// private decimal unitPrice; public decimal UnitPrice { get { return unitPrice; } set { unitPrice = value; } } /// /// 图书描述 /// private string contentDescription; public string ContentDescription { get { return contentDescription; } set { contentDescription = value; } } /// /// 图书作者描述 /// private string authorDescription; public string AuthorDescription { get { return authorDescription; } set { authorDescription = value; } } /// /// 图书作者评语 /// private string editorComment; public string EditorComment { get { return editorComment; } set { editorComment = value; } } /// /// 图书目录 /// private string toc; public string Toc { get { return toc; } set { toc = value; } } /// /// 图书的分类 /// private Category category; public Category Category { get { return category; } set { category = value; } } /// /// 图书点击 /// private int clicks; public int Clicks { get { return clicks; } set { clicks = value; } } } }
如果是这种关系,使用Datareader 就可能会出现异常,因为当代码读到 外键的时候,外键也要使用connection连接 这时就会抛出异常,所以
与数据进行动态交互,例如绑定到 Windows 窗体控件或组合并关联来自多个源的数据。
对数据执行大量的处理,而不需要与数据源保持打开的连接,从而将该连接释放给其他客户端使用。就使用DataSet或DataTable比较合适。
也许你不太明白,但是你可以这样简单的记住,当实体类或数据库设计存在主外键关系的时候,使用Datareader就要谨慎了! 不过也没关系,很多经验都是从Debug学到的。
就好像微软的视频一样,为爱Debug。