Feldmarshall
Feldmarshall

Reputation: 109

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?

Upvotes: 1

Views: 1071

Answers (3)

Roe
Roe

Reputation: 858

Just as sr28 pointed out, this will return an array. You could either add the array to the books list. I personally prefer using the method syntax.

I don't really understand why you would add the book to this list. But here you go. Since you already defined books you dont need to return it, you can simply add book to books.

public void AddBook()
{
    var book = db.books.FirstOrDefault(b => b.BookId == 1);
    books.add(book);
}

Upvotes: 1

Yong Shun
Yong Shun

Reputation: 51160

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.

Upvotes: 1

Vinceenzo
Vinceenzo

Reputation: 47

if I understand your problem correctly, the solution is simpler than expected, try making a where condition like this:

public class DataContext
{
LINQtoSQLDataContext db = new LINQtoSQLDataContext();
List<book> books = new List<book>();
public List<book> addBook()
{
    books = db.book.Where(x => x.bookId == 1).ToList();
    return books;
} 
}

Upvotes: 1

Related Questions