我如何改啊 我用list存储一个对象 其中这个对象中还有一个对象 可是我在数据库查讯中 提示未关闭数据库 可是改了 又是一打开数据库了
public IList<Book> GetBook() {
IList<Book> list = new List<Book>();
DBHelper db = new DBHelper();
string sql = "select * from Books";
int publisherId;
int caategoryId;
SqlDataReader reader = db.GetReader(sql);
while (reader.Read())
{
Book book = new Book();
book.Id = (int)reader["Id"];
book.Title = (string)reader["Title"];
book.Author = (string)reader["Author"]; ;
book.PublishDate = (DateTime)reader["PublishDate"];
book.ISBN = (string)reader["ISBN"];
book.WordsCount = (int)reader["WordsCount"];
book.UnitPrice = (decimal)reader["UnitPrice"];
book.ContentDescription = (string)reader["ContentDescription"];
book.AurhorDescription = (string)reader["AurhorDescription"];
book.EditorComment = (string)reader["EditorComment"];
book.TOC = (string)reader["TOC"];
book.Clicks = (int)reader["Clicks"];
publisherId = (int)reader["PublisherId"];
caategoryId = (int)reader["CategoryId"];
book.Publisher = new PublisherService().GetPublisherById(publisherId);
book.Category = new CategoryService().GetCategoryById(caategoryId);
list.Add(book);
}
reader.Close();
return list;
}
public IList<Book> GetBook() {
IList<Book> list = new List<Book>();
DBHelper db = new DBHelper();
string sql = "select * from Books";
int publisherId;
int caategoryId;
SqlDataReader reader = db.GetReader(sql);
while (reader.Read())
{
Book book = new Book();
book.Id = (int)reader["Id"];
book.Title = (string)reader["Title"];
book.Author = (string)reader["Author"]; ;
book.PublishDate = (DateTime)reader["PublishDate"];
book.ISBN = (string)reader["ISBN"];
book.WordsCount = (int)reader["WordsCount"];
book.UnitPrice = (decimal)reader["UnitPrice"];
book.ContentDescription = (string)reader["ContentDescription"];
book.AurhorDescription = (string)reader["AurhorDescription"];
book.EditorComment = (string)reader["EditorComment"];
book.TOC = (string)reader["TOC"];
book.Clicks = (int)reader["Clicks"];
publisherId = (int)reader["PublisherId"];
caategoryId = (int)reader["CategoryId"];
book.Publisher = new PublisherService().GetPublisherById(publisherId);
book.Category = new CategoryService().GetCategoryById(caategoryId);
list.Add(book);
}
reader.Close();
return list;
}
book.Category = new CategoryService().GetCategoryById(caategoryId);
你放到reader.close()后赋值,就是重新循环list 给上面的赋值
List<Book> list = new List<Book>();
var bookArray = from books in DataContext.Books;
foreach(var item in bookArray)
{
Book bk = new Book();
...
list.Add(bk);
}
可以实现的
如IDataReader