Search code examples
c#linq-to-sql

Add objects from database to a List, using LINQ to SQL


I have a table books and i want to put all of its contents into a List<book> (right now i'am stuck at adding a single element). I tried

public class DataContext
{
    LINQtoSQLDataContext db = new LINQtoSQLDataContext();
    List<book> books = new List<book>();
    public List<book> addBook()
    {
        books.Add((book)from book in db.books where book.bookID == 1 select book);
        return books;
    }
}

But when i try to set it as the source of my wpf dataGrid, it throws an error:

Unable to cast object of type 'System.Data.Linq.DataQuery`1[DataLayer.book]' to type 'DataLayer.book'.

So the question is, how do i properly convert data from the database to a list?


Solution

  • Just return the List of book as below:

    public List<book> addBook()
    {
        return (from book in db.books 
            where book.bookID == 1 
            select book)
            .ToList();
    }
    

    And it's weird to name the method addBook as the method's outcome is to return a list of book.

    Name it as: public List<book> GetBooks()

    While List<T>.Add(T) Method only allow to add single item to list, to add multiple items into list, you need List<T>.AddRange(IEnumerable<T>) Method.